-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSort-list.cc
51 lines (50 loc) · 1.24 KB
/
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
43
44
45
46
47
48
49
50
51
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//use merge sort
ListNode *sortList(ListNode *head) {
if(head == nullptr || head->next == nullptr) return head;
//divide
ListNode *lhs(head), *rhs(nullptr);
ListNode *fast(head->next), *slow(head);
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
rhs = slow->next;
slow->next = nullptr;
lhs = sortList(lhs);
rhs = sortList(rhs);
//merge
return mergeList(lhs, rhs);
}
private:
ListNode *mergeList(ListNode *lhs, ListNode *rhs) {
ListNode dummy(-1), *rear(&dummy);
while(lhs && rhs) {
if(lhs->val < rhs->val) {
rear->next = lhs;
lhs = lhs->next;
}
else {
rear->next = rhs;
rhs = rhs->next;
}
rear = rear->next;
}
if(lhs) {
rear->next = lhs;
}
if(rhs) {
rear->next = rhs;
}
return dummy.next;
}
};