-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_MergeSortLL.cpp
125 lines (104 loc) · 2.4 KB
/
GFG_MergeSortLL.cpp
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
https://practice.geeksforgeeks.org/problems/sort-a-linked-list/1
Merge Sort for Linked List
*/
// { Driver Code Starts
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
// } Driver Code Ends
/* Structure of the linked list node is as
struct Node
{
int data;
struct Node* next;
Node(int x) { data = x; next = NULL; }
};
*/
class Solution{
public:
//Function to sort the given linked list using Merge Sort.
Node* mergeSort(Node* head) {
if(!head || !head->next)
return head;
Node* mid = findMiddle(head);
Node* right = mid->next;
Node* left = head;
mid->next = nullptr;
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
Node* findMiddle(Node* head)
{
Node* slow = head;
Node* fast = head->next;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
Node* merge(Node* l1, Node *l2)
{
Node *dummyHead = new Node(0);
Node *ptr = dummyHead;
while(l1 && l2)
{
if(l1->data <= l2->data){
ptr->next = l1;
l1 = l1->next;
}
else{
ptr->next = l2;
l2 = l2->next;
}
ptr = ptr->next;
}
if(l1)
ptr->next = l1;
else
ptr->next = l2;
return dummyHead->next;
}
};
// { Driver Code Starts.
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void push(struct Node** head_ref, int new_data) {
Node* new_node = new Node(new_data);
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
long test;
cin >> test;
while (test--) {
struct Node* a = NULL;
long n, tmp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> tmp;
push(&a, tmp);
}
Solution obj;
a = obj.mergeSort(a);
printList(a);
}
return 0;
} // } Driver Code Ends