-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLinkedListMergeSort.cpp
More file actions
115 lines (103 loc) · 1.98 KB
/
LinkedListMergeSort.cpp
File metadata and controls
115 lines (103 loc) · 1.98 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
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
#include <bits/stdc++.h>
using namespace std;
class node {
public:
node *next;
int data;
node(int x) {
data = x;
next = NULL;
}
};
void insertAtHead(node *&head, int data) {
if (head == NULL) {
head = new node(data);
return;
} else {
node *n = new node(data);
n->next = head;
head = n;
return;
}
}
int length(node *head) {
int cnt = 0;
while (head != NULL) {
cnt++;
head = head->next;
}
return cnt;
}
node *takeInput() {
int d;
cin >> d;
node *head = NULL;
while (d != -1) {
insertAtHead(head, d);
cin >> d;
}
return head;
}
node* mergeLL(node*head1,node*head2){
//Base case
if(head1 == NULL){
return head2;
}
if(head2==NULL){
return head1;
}
//Recursive case
node* temp;
if(head1->data<head2->data){
temp = head1;
temp->next = mergeLL(head1->next,head2);
}
else{
temp = head2;
temp->next = mergeLL(head1,head2->next);
}
return temp;
}
node* mergeSort(node*head){
//Base case
if(head == NULL || head->next == NULL){
return head;
}
//recursive case
//Break LL in two
node*mid = head;
for(int i=1;i<length(head)/2;i++){
mid = mid->next;
}
node*a = head;
node*b = mid->next;
mid->next = NULL;
//Recursively sort the two parts
a = mergeSort(a);
b = mergeSort(b);
//merge the two sorted parts in final LL
return mergeLL(a,b);
}
void print(node *head) {
while (head != NULL) {
cout << head->data << "-> ";
head = head->next;
}
cout << endl;
}
istream &operator>>(istream &is, node *&head) {
head = takeInput();
return is;
}
ostream &operator<<(ostream &os, node *head) {
print(head);
return os;
}
int main() {
node *head = NULL;
cin >> head;
cout << head;
node* newHead = mergeSort(head);
cout<<newHead;
return 0;
}