forked from ysdeal/LeetJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeKLists.java
More file actions
executable file
·65 lines (60 loc) · 1.43 KB
/
mergeKLists.java
File metadata and controls
executable file
·65 lines (60 loc) · 1.43 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
class ListNode{
int val;
ListNode next;
ListNode (int x){
val = x;
next = null;
}
}
public class mergeKLists{
public static void main(String[] args) {
ListNode l1 = new ListNode(5);
l1.next = new ListNode(9);
ListNode l2 = new ListNode(6);
l2.next = new ListNode(7);
ArrayList<ListNode> lists = new ArrayList<ListNode>(Arrays.asList(l1,l2));
ListNode res = mergeK(lists);
while (res != null){
System.out.print(res.val + "->");
res = res.next;
}
return;
}
public static ListNode mergeK(ArrayList<ListNode> lists){
if (lists.size() == 0)
return null;
//PriorityQueue
PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
@Override
public int compare(ListNode a, ListNode b){
return a.val - b.val;
}
});
for(ListNode l : lists){
if (l != null)
heap.add(l);
}
ListNode head = new ListNode(0);
ListNode cur = head;
while(heap.size() > 0){
ListNode tp = heap.poll();
cur.next = tp;
if(tp.next != null)
heap.add(tp.next);
cur = cur.next;
}
return head.next;
}
}