-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeSortLinkedList.cpp
More file actions
71 lines (64 loc) · 1.79 KB
/
mergeSortLinkedList.cpp
File metadata and controls
71 lines (64 loc) · 1.79 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
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* sortList(ListNode* head) {
if(head==NULL || head->next == NULL)
return head;
ListNode * mid = getMid(head);
ListNode * left = sortList(head);
ListNode * right = sortList(mid);
return merge(left, right);
}
ListNode*merge(ListNode *list1, ListNode *list2){
ListNode *temp = new ListNode(0);
ListNode *remember = temp;
while(list1 && list2){
if(list1->val < list2->val){
temp->next = list1;
list1 = list1->next;
}else {
temp->next = list2;
list2 = list2->next;
}
temp = temp->next;
}
if(list1)
temp->next = list1;
else
temp->next = list2;
return remember->next;
}
ListNode * getMid(ListNode *head){
ListNode *temp = head;
ListNode *slow = head;
ListNode *fast = head;
while(fast!=NULL && fast->next!=NULL){
temp = slow;
slow = slow->next;
fast = fast->next->next;
}
temp->next = NULL; //split
return slow;
}
};
int main(){
ListNode * root = new ListNode(10);
root->next = new ListNode(1);
root->next->next = new ListNode(60);
root->next->next->next = new ListNode(30);
root->next->next->next->next = new ListNode(5);
Solution s;
ListNode * ans = s.sortList(root);
while(ans){
cout<<ans->val<< " ";
ans = ans->next;
}
}