forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths3.cpp
More file actions
39 lines (38 loc) · 1.07 KB
/
Copy paths3.cpp
File metadata and controls
39 lines (38 loc) · 1.07 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
38
39
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
void quickSort(ListNode *begin, ListNode *end) {
if (begin == end || begin->next == end) return;
auto p = partition(begin, end);
quickSort(begin, p.first);
quickSort(p.second, end);
}
pair<ListNode*, ListNode*> partition(ListNode *begin, ListNode *end) {
int pivot = begin->val;
ListNode *eqHead = begin, *eqTail = begin, *p = begin->next;
while (p != end) {
if (p->val <= pivot) {
if (p->val < pivot) {
swap(eqHead->val, p->val);
eqHead = eqHead->next;
}
swap(p->val, eqTail->next->val);
eqTail = eqTail->next;
}
p = p->next;
}
return make_pair(eqHead, eqTail->next);
}
public:
ListNode* sortList(ListNode* head) {
quickSort(head, NULL);
return head;
}
};