-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0147-insertion-sort-list.cpp
More file actions
66 lines (54 loc) · 1.91 KB
/
0147-insertion-sort-list.cpp
File metadata and controls
66 lines (54 loc) · 1.91 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *nxt = head->next,
*crr = head,
*prev = nullptr,
*curr = nullptr,
*sortHead = nullptr,
*sortTail = nullptr;
// crr is the pointer of the current element being inserted
while (crr != nullptr) {
// either the element is the first one or the smallest one
if (sortHead == nullptr || sortTail == nullptr || crr->val < sortHead->val) {
crr->next = sortHead;
sortHead = crr;
if (sortTail == nullptr) sortTail = crr;
}
// insert to tail
else if (crr->val >= sortTail->val) {
sortTail->next = crr;
crr->next = nullptr;
sortTail = crr;
}
// insert in the middle
else {
// start searching linked list from the sorted part
prev = sortHead;
curr = sortHead->next;
while (curr != sortTail->next && curr) {
// insert into correct position if a match is found
if (crr->val <= curr->val) {
prev->next = crr;
crr->next = curr;
break;
}
prev = curr;
curr = curr->next;
}
}
// move to the next element;
crr = nxt;
if (crr) nxt = crr->next;
}
return sortHead;
}
};