-
Notifications
You must be signed in to change notification settings - Fork 0
/
62_Sort_List
69 lines (54 loc) · 1.74 KB
/
62_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
class Solution {
public:
ListNode* sortList(ListNode* head) {
//If List Contain a Single or 0 Node
if(head == NULL || head ->next == NULL)
return head;
ListNode *temp = NULL;
ListNode *slow = head;
ListNode *fast = head;
// 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)
while(fast != NULL && fast -> next != NULL)
{
temp = slow;
slow = slow->next; //slow increment by 1
fast = fast ->next ->next; //fast incremented by 2
}
temp -> next = NULL; //end of first left half
ListNode* l1 = sortList(head); //left half recursive call
ListNode* l2 = sortList(slow); //right half recursive call
return mergelist(l1, l2); //mergelist Function call
}
//MergeSort Function O(n*logn)
ListNode* mergelist(ListNode *l1, ListNode *l2)
{
ListNode *ptr = new ListNode(0);
ListNode *curr = ptr;
while(l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{
curr -> next = l1;
l1 = l1 -> next;
}
else
{
curr -> next = l2;
l2 = l2 -> next;
}
curr = curr ->next;
}
//for unqual length linked list
if(l1 != NULL)
{
curr -> next = l1;
l1 = l1->next;
}
if(l2 != NULL)
{
curr -> next = l2;
l2 = l2 ->next;
}
return ptr->next;
}
};