-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_K_Sorted_Linked_List.cpp
More file actions
134 lines (112 loc) · 2.78 KB
/
Merge_K_Sorted_Linked_List.cpp
File metadata and controls
134 lines (112 loc) · 2.78 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
//{ Driver Code Starts
// C++ program to merge k sorted arrays of size n each
#include <bits/stdc++.h>
using namespace std;
// A Linked List node
struct Node {
int data;
Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
/* Function to print nodes in a given linked list */
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
cout << endl;
}
// } Driver Code Ends
/*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.
Node* mergeKLists(vector<Node*>& arr) {
Node* head = new Node(-1);
Node* dummy = head;
vector <int> a;
for(int i = 0; i < arr.size(); i++)
{
Node* temp = arr[i];
while(temp != NULL)
{
a.push_back(temp->data);
temp = temp->next;
}
}
sort(a.begin(), a.end());
int j = 0;
for(int i = 0; i < arr.size(); i++)
{
Node* temp = arr[i];
while(temp != NULL)
{
temp->data = a[j++];
temp = temp->next;
}
}
for(int i = 0; i < arr.size(); i++)
{
Node* temp = arr[i];
while(temp != NULL)
{
head->next = temp;
head = temp;
temp = temp->next;
}
}
return dummy->next;
}
};
//{ Driver Code Starts.
// Driver program to test the above functions
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<Node*> arr;
vector<int> nums;
string input;
getline(cin, input); // Read the entire line for the array elements
stringstream ss(input);
int number;
while (ss >> number) {
nums.push_back(number);
}
int ind = 0;
int N = nums.size();
while (ind < N) {
int n = nums[ind++];
int x = nums[ind++];
Node* head = new Node(x);
Node* curr = head;
n--;
for (int i = 0; i < n; i++) {
x = nums[ind++];
Node* temp = new Node(x);
curr->next = temp;
curr = temp;
}
arr.push_back(head);
}
Solution obj;
Node* res = obj.mergeKLists(arr);
printList(res);
}
return 0;
}
// } Driver Code Ends