-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMergeKLinkedList.java
More file actions
44 lines (40 loc) · 1.08 KB
/
MergeKLinkedList.java
File metadata and controls
44 lines (40 loc) · 1.08 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
package LinkedList;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* @author Vishal Singh
* 7/25/2021
* @link https://practice.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1
*/
public class MergeKLinkedList {
class Node {
int data;
Node next;
Node(int key) {
data = key;
next = null;
}
}
class Solution {
Node mergeKList(Node[] arr, int K) {
PriorityQueue<Node> pq = new PriorityQueue<>((a, b) -> a.data - b.data);
pq.addAll(Arrays.asList(arr));
Node res = null, curr = null;
while (!pq.isEmpty()) {
Node temp = pq.poll();
if (res == null) {
res = new Node(temp.data);
curr = res;
}
else {
curr.next = new Node(temp.data);
curr = curr.next;
}
if(temp.next != null) {
pq.add(temp.next);
}
}
return res;
}
}
}