This repository was archived by the owner on May 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.Sort List.cpp
More file actions
63 lines (49 loc) · 1.6 KB
/
148.Sort List.cpp
File metadata and controls
63 lines (49 loc) · 1.6 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
/*Question: Given the head of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?*/
/**
* 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* sortList(ListNode* head) {
if(!head || !head->next)
return head;
ListNode *mid = findMid(head);
ListNode *list1 = sortList(head);
ListNode *list2 = sortList(mid);
ListNode *newhead = merge(list1,list2);
return newhead;
}
ListNode* findMid(ListNode *head)
{
ListNode *slow = head, *fast = head, *temp;
while(fast && fast->next)
{
temp=slow;
slow = slow->next;
fast = fast->next->next;
}
temp->next = NULL;
return slow;
}
ListNode *merge(ListNode *list1, ListNode* list2)
{
if(!list1) return list2;
if(!list2) return list1;
if(list1->val < list2->val)
{
list1->next = merge(list1->next,list2);
return list1;
}
list2->next = merge(list1,list2->next);
return list2;
}
};
//Solution takes O(n logn) time and O(1) memory (i.e. constant space)