forked from ShivamDubey7/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathMerge K sorted Linked Lists
117 lines (97 loc) · 1.95 KB
/
Merge K sorted Linked Lists
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* next;
Node(int x){
data = x;
next = NULL;
}
};
void printList(Node* node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
cout<<endl;
}
/*Linked list Node structure
struct Node
{
int data;
Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution{
public:
//Function to merge K sorted linked list.
struct comparator{
bool operator()(Node* h1, Node* h2){
return h1->data > h2->data;
}
};
Node * mergeKLists(Node *arr[], int K)
{
// Your code here
priority_queue<Node*, vector<Node*>, comparator> pq;
int idx =0;
while(idx < K){
if(arr[idx]!=NULL){
pq.push(arr[idx]);
idx++;
}
}
Node* dummyNode= new Node(-1);
Node* temp= dummyNode;
while(!pq.empty()){
Node* topEl= pq.top();
pq.pop();
temp->next= topEl;
temp=temp->next;
if(topEl->next != NULL){
pq.push(topEl->next);
}
}
Node* head= dummyNode->next;
return head;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
int N;
cin>>N;
struct Node *arr[N];
for(int j=0;j<N;j++)
{
int n;
cin>>n;
int x;
cin>>x;
arr[j]=new Node(x);
Node *curr = arr[j];
n--;
for(int i=0;i<n;i++)
{
cin>>x;
Node *temp = new Node(x);
curr->next =temp;
curr=temp;
}
}
Solution obj;
Node *res = obj.mergeKLists(arr,N);
printList(res);
}
return 0;
}