-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
29 lines (28 loc) · 876 Bytes
/
MergeKSortedLists.java
File metadata and controls
29 lines (28 loc) · 876 Bytes
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeTwoSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
PriorityQueue<ListNode> heap = new PriorityQueue<>(new Comparator<ListNode>() {
public int compare(final ListNode n1, final ListNode n2) {
return Integer.compare(n1.val, n2.val);
}
});
for (ListNode node : lists)
if (node != null) heap.offer(node);
while (!heap.isEmpty()) {
ListNode node = heap.poll();
tail.next = node;
tail = tail.next;
if (node.next != null) heap.offer(node.next);
}
return dummy.next;
}
}