forked from MaskRay/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-list.cc
50 lines (48 loc) · 1.02 KB
/
sort-list.cc
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
// Sort List
// natural merge sort
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (! head)
return head;
for(;;) {
ListNode *p = head, *q, *r, *s, *head2 = NULL, *l = NULL;
bool ok = true;
while (p) {
q = p;
while (q->next && q->val <= q->next->val)
q = q->next;
q = q->next;
s = r = q;
if (s) {
while (s->next && s->val <= s->next->val)
s = s->next;
s = s->next;
}
if (q)
ok = false;
while (p != q || r != s)
if (r == s || p != q && p->val < r->val) {
if (l)
l->next = p;
else
head2 = p;
l = p;
p = p->next;
} else {
if (l)
l->next = r;
else
head2 = r;
l = r;
r = r->next;
}
p = s;
}
l->next = NULL;
head = head2;
if (ok) break;
}
return head;
}
};