/
Merge_k_Sorted_Lists.java
49 lines (35 loc) · 1.13 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
40
41
42
43
44
45
46
47
48
49
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists.size() == 0) return null;
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),
new Comparator<ListNode>(){
public int compare(ListNode a, ListNode b){
if(a.val > b.val) return 1;
else if(a.val == b.val) return 0;
else return -1;
}
});
for(ListNode i : lists)
if(i != null) q.add(i);
ListNode head = new ListNode(-1);
ListNode pre = head;
while(q.size() != 0){
ListNode temp = q.poll();
pre.next = temp;
if(temp.next != null) q.add(temp.next);
pre = pre.next;
}
return head.next;
}
}