-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion_Sort_List.cpp
54 lines (48 loc) · 1.51 KB
/
Insertion_Sort_List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *cur = head->next, *cur_next;
head->next = NULL;
while(true) {
cur_next = cur->next;
/* Insert the cur-node into the new sorted Linked-List */
if(cur->val <= head->val) {
cur->next = head;
head = cur;
} else {
ListNode *prev = head, *prev_next = head->next;
bool midInsert = false;
while(prev_next != NULL) {
if(prev->val < cur->val && cur->val <= prev_next->val) {
prev->next = cur;
cur->next = prev_next;
midInsert = true;
break;
} else {
prev = prev_next;
prev_next = prev_next->next;
}
}
/* The cur-node should be inserted into the tail of the new Linked-List. */
if(!midInsert) {
prev->next = cur;
cur->next = NULL;
}
}
cur = cur_next;
if(cur == NULL)
break;
}
return head;
}
};