-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion Sort List.cpp
44 lines (39 loc) · 1.11 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
/**
* 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 == nullptr) {
return nullptr;
}
ListNode *dummy = new ListNode(INT_MIN);
dummy->next = head;
ListNode *sorted = dummy;
bool swapped = false;
while (sorted->next != nullptr) {
ListNode *s = sorted->next;
for (ListNode *cur = dummy; cur != sorted; cur = cur->next) {
if (s->val <= cur->next->val) {
ListNode *t = cur->next;
sorted->next = s->next;
s->next = t;
cur->next = s;
swapped = true;
break;
}
}
if (!swapped) {
sorted = sorted->next;
} else {
swapped = false;
}
}
return dummy->next;
}
};