-
Notifications
You must be signed in to change notification settings - Fork 111
/
sort-list.cc
42 lines (40 loc) · 884 Bytes
/
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
// Sort List
// natural merge sort
class Solution {
public:
ListNode *sortList(ListNode *head) {
for(;;) {
ListNode *p = head, *q, *r, *s, *head2 = NULL, **l = &head2;
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) {
*l = p;
l = &p->next;
p = p->next;
} else {
*l = r;
l = &r->next;
r = r->next;
}
p = s;
}
*l = NULL;
head = head2;
if (ok) break;
}
return head;
}
};