-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeKsortedlist.java
More file actions
46 lines (41 loc) · 1.2 KB
/
Copy pathmergeKsortedlist.java
File metadata and controls
46 lines (41 loc) · 1.2 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2){
return Integer.compare(l1.val,l2.val);
}
}
*/
public class Solution {
class testcompare implements Comparator<ListNode>{
@Override
public int compare(ListNode a, ListNode b){
return Integer.compare(a.val,b.val);
}
}
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length==0){
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length,new testcompare());
ListNode head = new ListNode(0);
ListNode result = head;
for(int i=0;i<lists.length;i++){
if(lists[i]!=null)
pq.add(lists[i]);
}
while(!pq.isEmpty()){
ListNode tmp = pq.poll();
if(tmp.next != null)
pq.add(tmp.next);
result.next=tmp;
result = result.next;
}
return head.next;
}
}