forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort_LL.cpp
130 lines (114 loc) · 2.42 KB
/
merge_sort_LL.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
126
127
128
129
130
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* next;
};
struct node *head=NULL;
struct node *SortedMerge(struct node *a,struct node *b){
struct node *result=NULL;
struct node *temp;
if(a==NULL){
return b;
}
if(b==NULL){
return a;
}
if(a&&b){
if(a->data <= b->data){
temp=a;
a=temp->next;
}
else{
temp=b;
b=temp->next;
}
}
result=temp;
while(a&&b){
if(a->data <= b->data){
temp->next=a;
temp=a;
a=temp->next;
}
else{
temp->next=b;
temp=b;
b=temp->next;
}
}
if(a==NULL)
temp->next=b;
if(b==NULL)
temp->next=a;
return result;
}
void FrontBackSplit(struct node *head,struct node **a,struct node**b){
struct node *fast;
struct node *slow;
if(head==NULL||head->next==NULL){
*a=head;
*b=NULL;
}
else{
slow=head;
fast=head->next;
while(fast!=NULL){
fast=fast->next;
if(fast!=NULL){
slow=slow->next;
fast=fast->next;
}
}
*a=head;
*b=slow->next;
slow->next=NULL;
}
}
void mergeSort(struct node** headRef){
struct node* head=*headRef;
struct node *a;
struct node *b;
//Base Case -- length 0 or 1
if((head==NULL)||(head->next==NULL)){
return;
}
FrontBackSplit(head,&a,&b);
mergeSort(&a);
mergeSort(&b);
*headRef=SortedMerge(a,b);
}
void displayLLD(struct node *head){
struct node *temp=head;
while(temp!=NULL){
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL\n");
}
void insertAtBegin(int value){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=value;
if(head==NULL){
head=temp;
temp->next=NULL;
return;
}
temp->next=head;
head=temp;
}
int main(){
int n;
cin>>n;
int x;
for(int i=0;i<n;i++){
cin>>x;
insertAtBegin(x);
}
printf("Linked List\n");
displayLLD(head);
mergeSort(&head);
printf("Merge Sorted Linked List\n");
displayLLD(head);
}