-
Notifications
You must be signed in to change notification settings - Fork 1
/
148 Sort List .cpp
65 lines (65 loc) · 1.64 KB
/
148 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) {
return head;
}
function<int(ListNode *)> getLen = [] (ListNode *x) {
int s = 0;
while (x) {
s++;
x = x->next;
}
return s;
};
int len = getLen(head);
auto getKey = [&] () {
int k = rand() % len;
auto p = head;
while (k--) {
p = p->next;
}
return p->val;
};
int key = getKey();
ListNode *lHead = nullptr, *rHead = nullptr, *mHead = nullptr;
auto add = [] (ListNode *&h, ListNode *p) {
if (!h) {
h = p;
h->next = nullptr;
} else {
p->next = h;
h = p;
}
};
ListNode *next;
for (auto p = head; p; p = next) {
next = p->next;
if (p->val < key) {
add(lHead, p);
} else if (p->val > key) {
add(rHead, p);
} else {
add(mHead, p);
}
}
lHead = sortList(lHead);
rHead = sortList(rHead);
auto p = lHead;
if (lHead) {
for (; p->next; p = p->next);
p->next = mHead;
}
for (p = mHead; p->next; p = p->next);
p->next = rHead;
return lHead ? lHead : mHead;
}
};