forked from Vishal-Aggarwal0305/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeKSortedArrays.cpp
149 lines (116 loc) · 2.58 KB
/
MergeKSortedArrays.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//Problem Link: https://leetcode.com/problems/merge-k-sorted-lists/
/*
using divide and conquer approach to merge lists.
so merging first half and then second half.
then finally merging both of them.
*/
#include<bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
void printLists(ListNode* head) {
while(head!=NULL) {
cout<<head->val<<" ";
head = head->next;
}
cout<<endl;
}
void merge(ListNode** l1, ListNode** l2) {
ListNode** head = l1 ;
ListNode* prev=NULL;
ListNode *i, *j;
i = *l1;
j = *l2;
while((i!=NULL) && (j!=NULL)) {
if(i->val < j->val) {
if(prev==NULL) {
*head = i;
} else {
prev->next = i;
}
prev = i;
i = i->next;
} else {
if(prev==NULL) {
*head = j;
} else {
prev->next = j;
}
prev = j;
j = j->next;
}
}
while(i!=NULL) {
if(prev==NULL) {
*head = i;
} else {
prev->next = i;
}
prev = i;
i = i->next;
}
while(j!=NULL) {
if(prev==NULL) {
*head = j;
} else {
prev->next = j;
}
prev = j;
j = j->next;
}
}
void func(vector<ListNode*>& lists, int leftLimit, int rightLimit) {
if(leftLimit < rightLimit) {
int mid = leftLimit + (rightLimit -leftLimit)/2;
func(lists, leftLimit, mid);
func(lists, mid+1, rightLimit);
merge(&lists[leftLimit], &lists[mid+1]);
}
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
func(lists, 0, lists.size()-1);
if(lists.size()>=1){
return lists[0];
} else {
return NULL;
}
}
int main() {
vector<ListNode*> lists;
int n;
cout<<"Enter the number of lists:";
cin>>n;
for(int i=0; i<n; i++) {
int s, num;
cout<<"enter size of list:";
cin>>s;
ListNode *head = NULL, *cur ;
for(int i=0; i<s; i++) {
cin>>num;
ListNode* node = new ListNode(num);
if(head==NULL){
head = node;
} else {
cur->next = node;
}
cur = node;
}
cur->next = NULL;
lists.push_back(head);
}
for(int i=0; i<n; i++) {
printLists(lists[i]);
}
mergeKLists(lists);
if(n>0) {
printLists(lists[0]);
} else {
cout<<"No lists entered"<<endl;
}
return 0;
}