forked from Ayu-99/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Sort in LL.cpp
More file actions
133 lines (103 loc) · 2.38 KB
/
Merge Sort in LL.cpp
File metadata and controls
133 lines (103 loc) · 2.38 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
/*
Code: Merge Sort
Send Feedback
Sort a given linked list using Merge Sort.
You don't need to print the elements, just sort the elements and return the head of updated LL.
Input format :
Linked list elements (separated by space and terminated by -1)
Output format :
Updated LL elements (separated by space)
Constraints :
1 <= Length of LL <= 1000
Sample Input 1 :
1 4 5 2 -1
Sample Output 1 :
1 2 4 5
*/
// Following is the node structure
/**************
class node{
public:
int data;
node * next;
node(int data){
this->data=data;
this->next=NULL;
}
};
***************/
node *mergeLL(node *headA, node *headB){
node *ft=NULL, *fh=NULL;
while(headA!=NULL && headB!=NULL){
if(fh==NULL){
if(headA->data>headB->data){
ft=headB;
fh=headB;
headB=headB->next;
}else{
ft=headA;
fh=headA;
headA=headA->next;
}
}
else
{
if(headA->data>headB->data){
ft->next=headB;
ft=ft->next;
headB=headB->next;
}else{
ft->next=headA;
ft=ft->next;
headA=headA->next;
}
}
}
if(headA==NULL){
ft->next=headB;
}
if(headB==NULL){
ft->next=headA;
}
return fh;
}
node* mergeSort(node *head) {
//write your code here
if(head->next == NULL)
return head;
/*int l=0;
node *temp=head, *temp1=head;
while(temp!=NULL){
l++;
temp=temp->next;
}
int midIndex=l/2;
// //If length of linked list is even
// if(l%2==0){
// midIndex=(l-1)/2;
// }else{
// midIndex=(l/2);
// }
int i=0;
while(i!=midIndex){
i++;
temp1=temp1->next;
}
node *head2;
head2=temp1->next;
temp1->next=NULL;
*/
node* slow=head;
node* fast=head->next;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
node* head2=slow->next;
slow->next=NULL;
node *headA=mergeSort(head);
node *headB=mergeSort(head2);
//Merge two sorted linked list
node *fh=mergeLL(headA, headB);
return fh;
}