-
Notifications
You must be signed in to change notification settings - Fork 15
/
merge-k-sorted-lists.java
40 lines (32 loc) · 1.1 KB
/
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
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null || lists.size() == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue(lists.size(), new Comparator<ListNode>(){
public int compare(ListNode node1, ListNode node2){
return node1.val - node2.val;
}
});
for(ListNode node : lists){
if(node != null){
queue.add(node);
}
}
ListNode dummy = new ListNode(1);
ListNode runner = dummy;
while(!queue.isEmpty()){
ListNode current = queue.poll();
runner.next = current;
runner = runner.next;
current = current.next;
while (!queue.isEmpty() && current != null && current.val <= queue.peek().val) {
runner.next = current;
runner = runner.next;
current = current.next;
}
if(current != null){
queue.add(current);
}
}
return dummy.next;
}
}