Fork me on GitHub

Sort List

Description

###Quicksort

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
/**
* 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 == NULL || head->next == NULL) return head;
sort(head, NULL);
return head;
}

void sort(ListNode* start, ListNode* end) {
if (start == end || start->next == end) return;
ListNode* mid = partition(start, end);
sort(start, mid);
sort(mid->next, end);
}

ListNode* partition(ListNode* start, ListNode* end) {
int midValue = start->val;
ListNode* cur = start->next;
ListNode* mid = start;
while (cur != end) {
if (cur->val < midValue) {
mid = mid->next;
swap(mid->val, cur->val);
}
cur = cur->next;
}
swap(mid->val, start->val);
return mid;
}
};

Mergesort

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
/**
* 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 == NULL || head->next == NULL) return head;
ListNode* ret = sort(head);
return ret;
}

ListNode* sort(ListNode* start) {
if (!start || !start->next) return start;
ListNode* slow = start;
ListNode* quick = start;
while (quick && quick->next && quick->next->next) {
slow = slow->next;
quick = quick->next->next;
}
ListNode* left = sort(slow->next);
slow->next = NULL;
ListNode* right = sort(start);
return merge(left, right);
}

ListNode* merge(ListNode* left, ListNode* right) {
ListNode* fake = new ListNode(-1);
ListNode* cur = fake;
while (left != NULL && right != NULL) {
if (left->val < right->val){
cur->next = left;
left = left->next;
}else {
cur->next = right;
right = right->next;
}
cur = cur->next;
}
cur->next = left ? left : right;
ListNode* ret = fake->next;
delete fake;
return ret;
}
};