-
Notifications
You must be signed in to change notification settings - Fork 0
/
148. Sort List
89 lines (77 loc) · 2 KB
/
148. Sort List
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* 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* getMid(ListNode* head)
{
ListNode* slow = head;
ListNode* fast = head -> next;
while(fast != NULL && fast -> next != NULL)
{
fast = fast -> next -> next;
slow = slow -> next;
}
return slow;
}
ListNode* merge(ListNode* left, ListNode* right)
{
if(left == NULL)
return right;
if(right == NULL)
return left;
ListNode* ans = new ListNode(-1);
ListNode* temp = ans;
while(left != NULL && right != NULL)
{
if(right -> val < left -> val)
{
temp -> next = right;
temp = right;
right = right ->next;
}
else
{
temp -> next = left;
temp = left;
left = left -> next;
}
}
while(left != NULL)
{
temp -> next = left;
temp = left;
left = left -> next;
}
while(right != NULL)
{
temp -> next = right;
temp = right;
right = right ->next;
}
return ans -> next;
}
ListNode* sortList(ListNode* head) {
// base case
if(head == NULL || head -> next == NULL)
return head;
//divide list into two halves
ListNode* mid = getMid(head);
ListNode* left = head;
ListNode* right = mid -> next;
mid -> next = NULL;
//recursive calls for sort the both halves
left = sortList(left);
right = sortList(right);
//merge the halves
ListNode* ans = merge(left, right);
return ans;
}
};