-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23-merge-k-sorted-lists.java
40 lines (40 loc) · 1.12 KB
/
23-merge-k-sorted-lists.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Comparator<ListNode> cmp;
cmp = new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
// TODO Auto-generated method stub
return o1.val-o2.val;
}
};
Queue<ListNode> pq = new PriorityQueue<>(cmp);
ListNode mergedHead = new ListNode();
ListNode result = mergedHead;
for (ListNode ln : lists) {
if(ln != null) {
pq.add(ln);
}
}
while (!pq.isEmpty()) {
ListNode min = pq.poll();
mergedHead.next = min;
mergedHead = mergedHead.next;
if (min.next != null) {
min = min.next;
pq.add(min);
}
}
return result.next;
}
}