Repository navigation
Expand file tree
/
Copy pathmerge_sort_linked_list.cpp
More file actions
135 lines (101 loc) · 2.34 KB
/
Copy pathmerge_sort_linked_list.cpp
File metadata and controls
135 lines (101 loc) · 2.34 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
class node{
public:
int data;
node* next;
node(int val){
this->data = val;
this->next = NULL;
}
};
void append(node** head, int val){
node* prev = *head;
node* pcrawl = *head;
while(pcrawl!=NULL){
prev = pcrawl;
pcrawl = pcrawl->next;
}
node* to_insert = new node(val);
if(prev == NULL){
*head = to_insert;
return;
}
prev->next = to_insert;
return;
}
void print_soln(node* head){
cout<<"linked list: ";
while(head!=NULL){
cout<<" -> "<<head->data;
head = head->next;
}
cout<<"\n";
return;
}
node* merge(node* a, node* b){
node* head1 = NULL; // initialize head1 with NULL
node* pcrawl_a = a;
node* pcrawl_b = b;
while(pcrawl_a!=NULL && pcrawl_b!=NULL){
if(pcrawl_a->data <= pcrawl_b->data){
append(&head1, pcrawl_a->data);
pcrawl_a=pcrawl_a->next;
}
else{
append(&head1, pcrawl_b->data);
pcrawl_b=pcrawl_b->next;
}
}
if(pcrawl_a==NULL){
while(pcrawl_b!=NULL){
append(&head1, pcrawl_b->data);
pcrawl_b=pcrawl_b->next;
}
}
if(pcrawl_b==NULL){
while(pcrawl_a!=NULL){
append(&head1, pcrawl_a->data);
pcrawl_a=pcrawl_a->next;
}
}
return head1;
}
void split_list(node* head, node** a, node** b){
if(head == NULL){return;}
node* slow = head;
node* fast = head->next; //* make fast point to head->next
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
*a = head;
*b = slow->next;
slow->next=NULL;
return;
}
void merge_sort(node** head){
if(*head == NULL || (*head)->next==NULL){return;}
node* a=NULL;
node* b=NULL;
split_list(*head, &a, &b);
merge_sort(&a);
merge_sort(&b);
*head = merge(a,b);
return;
}
int main(){
node* head = NULL;
append(&head, 15);
append(&head, 10);
append(&head, 5);
append(&head, 20);
append(&head, 3);
append(&head, 2);
print_soln(head);
merge_sort(&head);
cout<<"\nlist after sorting: ";
print_soln(head);
return 0;
}