-
Notifications
You must be signed in to change notification settings - Fork 0
/
147-Insertion Sort List.cpp
39 lines (39 loc) · 1.16 KB
/
147-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
/**
* 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 || !head->next) return head;
ListNode* prev = head;
ListNode* curr = head->next;
// ListNode* dummyHead = new ListNode(0);
//dummyHead.next = head;
ListNode dummyHead(0);
dummyHead.next = head;
// head ~ prev is sorted, we need the insert curr into sorted part
while(curr){
ListNode* tmp = curr->next;
ListNode* insertPoint = &dummyHead;
while(insertPoint != prev && curr->val > insertPoint->next->val){
insertPoint = insertPoint->next;
}
if(insertPoint == prev){
prev = curr;
curr = curr->next;
} else{
curr->next = insertPoint->next;
insertPoint->next = curr;
prev->next = tmp;
curr = tmp;
}
}
// return dummyHead->next;
return dummyHead.next;
}
};