# [LeetCode] Insertion Sort List

Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.

First, a quick recap of insertion sort:

Start from the second element (simply a[1] in array and the annoying head -> next -> val in linked list), each time when we see a node with val smaller than its previous node, we scan from the head and find the position that the current node should be inserted. Since a node may be inserted before head, we create a new_head that points to head. The insertion operation, however, is a little easier for linked list.

Now comes the code:

 1 class Solution {
2 public:
3     ListNode* insertionSortList(ListNode* head) {
4         ListNode* new_head = new ListNode(0);
6         ListNode* pre = new_head;
7         ListNode* cur = head;
8         while (cur) {
9             if (cur -> next && cur -> next -> val < cur -> val) {
10                 while (pre -> next && pre -> next -> val < cur -> next -> val)
11                     pre = pre -> next;
12                 /* Insert cur -> next after pre.*/
13                 ListNode* temp = pre -> next;
14                 pre -> next = cur -> next;
15                 cur -> next = cur -> next -> next;
16                 pre -> next -> next = temp;
17                 /* Move pre back to new_head. */
18                 pre = new_head;
19             }
20             else cur = cur -> next;
21         }
22         ListNode* res = new_head -> next;
24         return res;
25     }
26 };

|
7月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List

22 1
|
7月前
|
C++
Leetcode Copy List with Random Pointer（面试题推荐）

30 0
|
7月前
Leetcode 19.Remove Nth Node From End of List

23 0
|
1月前
|
C++ 容器
【C++】STL容器——探究List与Vector在使用sort函数排序的区别（14）
【C++】STL容器——探究List与Vector在使用sort函数排序的区别（14）
40 0
|
1月前
|

「LeetCode合集」链表（List）及经典问题
「LeetCode合集」链表（List）及经典问题
34 0
|
11月前
|

SGI-STL源码剖析之list::sort()
SGI-STL源码剖析之list::sort()
83 0
LeetCode 75 Sort Colors 颜色分类（荷兰国旗）
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
73 0
|

LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
87 0
|
1天前
|
Java API

9 3
|
3天前
|
Java 索引