-
Notifications
You must be signed in to change notification settings - Fork 257
/
insertion-sort-list.cpp
45 lines (40 loc) · 1.01 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
// Time: O(n^2)
// Space: O(1)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
ListNode dummy{numeric_limits<int>::min()};
auto curr = head;
ListNode *position = nullptr;
while (curr) {
position = findInsertPosition(&dummy, curr->val);
ListNode *tmp = curr->next;
curr->next = position->next;
position->next = curr;
curr = tmp;
}
return dummy.next;
}
ListNode* findInsertPosition(ListNode *head, int x) {
ListNode *prev = nullptr;
for (auto curr = head; curr && curr->val <= x;
prev = curr, curr = curr->next);
return prev;
}
};