forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSortList.cpp
More file actions
37 lines (37 loc) · 1 KB
/
insertionSortList.cpp
File metadata and controls
37 lines (37 loc) · 1 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
/**
* 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 == NULL) return head;
ListNode *cur = head->next, *last = head;
while (cur != NULL) {
ListNode *next = cur->next;
if (cur->val <= head->val) {
cur->next = head;
head = cur;
} else if (cur->val >= last->val) {
last = cur;
} else {
ListNode *t = head;
while (true) {
if (cur->val > t->val && cur->val <= t->next->val) {
cur->next = t->next;
t->next = cur;
break;
}
t = t->next;
}
}
last->next = next;
cur = next;
}
return head;
}
};