-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
51 lines (42 loc) · 1.3 KB
/
MergeKSortedLists.java
File metadata and controls
51 lines (42 loc) · 1.3 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
package LinkedLists;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MergeKSortedLists {
public static void main(String[] args) {
// Contains the head nodes of all the list.
Node[] lists = new Node[4];
Node head = mergeKLists(lists);
}
public static Node mergeKLists(Node[] lists) {
PriorityQueue<Node> queue = new PriorityQueue<>(new NodeComparator());
int K = lists.length;
Node head = new Node(0);
Node last = head;
for (Node list : lists) {
if (list != null) {
queue.add(list);
}
}
if (queue.isEmpty()) return null;
while (!queue.isEmpty()) {
// Smallest Element Is Added To List.
Node curr = queue.poll();
last.next = curr;
last = last.next;
// Next Element of the element added.
if (curr.next != null) {
queue.add(curr.next);
}
}
return head.next;
}
static class NodeComparator implements Comparator<Node> {
public int compare(Node k1, Node k2) {
if (k1.data > k2.data)
return 1;
else if (k1.data < k2.data)
return -1;
return 0;
}
}
}