-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.cpp
More file actions
41 lines (38 loc) · 982 Bytes
/
InsertionSortList.cpp
File metadata and controls
41 lines (38 loc) · 982 Bytes
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
/**
Sort a linked list using insertion sort.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//The key is to understand is sorted insert algorithm
void insert(ListNode* head, ListNode* tail, ListNode* node) {
ListNode* curr = head;
while (curr->next->val < node->val) {
curr = curr->next;
}
tail->next = node->next;
node->next = curr->next;
curr->next = node;
}
ListNode *insertionSortList(ListNode *head) {
ListNode dummy(INT_MIN);
dummy.next = head;
ListNode* curr = &dummy;
while (curr->next) {
if (curr->next->val >= curr->val) {
curr = curr->next;
}
else {
insert(&dummy, curr, curr->next);
}
}
return dummy.next;
}
};