-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.cpp
More file actions
50 lines (50 loc) · 1.34 KB
/
148.cpp
File metadata and controls
50 lines (50 loc) · 1.34 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
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* left, ListNode* right){
if(!left)
return right;
if(!right)
return left;
ListNode* res = new ListNode(0);
ListNode* curr = res;
while(left && right){
if(left->val < right->val){
curr->next = left;
left = left->next;
}
else{
curr->next = right;
right = right->next;
}
curr = curr->next;
}
curr->next = (left!=NULL)?left:right;
return res->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next)
return head;
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = head;
while(fast && fast->next){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode* left = sortList(head);
ListNode* right = sortList(slow);
return merge(left,right);
}
};