-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortList.cpp
39 lines (38 loc) · 1 KB
/
sortList.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeSort(ListNode *l, ListNode *r) {
ListNode *temp = new ListNode(0);
ListNode *h = temp;
while(l && r) {
if (l->val < r->val) {
h->next = l;
l = l->next;
} else {
h->next = r;
r = r->next;
}
h = h->next;
}
h->next = l == NULL ? r : l;
return temp->next;
}
ListNode* sortList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *slow = head, *fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *middle = slow->next;
slow->next = NULL;
return mergeSort(sortList(head), sortList(middle));
}
};