-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort List
35 lines (34 loc) · 1.21 KB
/
Sort List
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
/**
*Sort List Total Accepted: 15414 Total Submissions: 76382 My Submissions
*Sort a linked list in O(n log n) time using constant space complexity.
*/
class Solution {
public:
ListNode *sortList(ListNode *head) {
return quicksort(head, NULL);
}
ListNode *quicksort(ListNode *head, ListNode *tail) {
if (!head) return NULL;
if (head -> next == tail) return head;
ListNode *nexthead = head;
while (nexthead -> next && nexthead -> next -> val == head -> val) nexthead = nexthead -> next;
ListNode *prehead = head, *posthead = nexthead, *p = nexthead -> next;
while (p != tail) {
if (p -> val < head -> val) {
ListNode *tmp1 = p -> next;
ListNode *tmp2 = prehead;
prehead = p;
prehead -> next = tmp2;
p = tmp1;
} else {
posthead -> next = p;
posthead = p;
p = p -> next;
}
}
posthead -> next = tail;
if (nexthead -> next != tail) nexthead -> next = quicksort(nexthead -> next, tail);
if (prehead == head) return head;
else return quicksort(prehead, head);
}
};