-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeKSortedLists.java
65 lines (54 loc) · 1.12 KB
/
MergeKSortedLists.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package ProjectFiles;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Comparator;
/**
*
* @author ma64
*
*/
public class MergeKSortedLists {
public static void main(String[] args) {
}
public static ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0){
return null;
}
ListNode result = null;
PriorityQueue<ListNode> q = new PriorityQueue<>(lists.length, new Comparator<ListNode>(){
@Override
public int compare(ListNode n1, ListNode n2){
if(n1.val < n2.val)
return -1;
else if(n1.val == n2.val)
return 0;
else
return 1;
}
});
for(int i = 0; i < lists.length; i++){
if(lists[i] != null){
q.add(lists[i]);
}
}
ListNode nodeEnd = null;
while(q.peek() != null){
ListNode removedNode = q.poll();
if(result == null){
result = removedNode;
if(removedNode.next != null){
q.add(removedNode.next);
}
nodeEnd = result;
}
else{
nodeEnd.next = removedNode;
nodeEnd = removedNode;
if(removedNode.next != null){
q.add(removedNode.next);
}
}
}
return result;
}
}