Skip to content

Commit cc40f19

Browse files
committed
Add Solution.java to problems 0023
1 parent 7665b70 commit cc40f19

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
import java.util.*;
10+
11+
class Solution {
12+
public ListNode mergeKLists(ListNode[] lists) {
13+
ListNode res = new ListNode(0), move = res;
14+
PriorityQueue<ListNode> queue = new PriorityQueue<>(3, new Comparator<ListNode>() {
15+
public int compare(ListNode o1, ListNode o2) {
16+
return o1.val - o2.val;
17+
}
18+
});
19+
20+
for (ListNode node : lists) {
21+
if (node != null) {
22+
queue.offer(node);
23+
}
24+
}
25+
26+
while (!queue.isEmpty()) {
27+
ListNode poll = queue.poll();
28+
move.next = poll;
29+
move = move.next;
30+
31+
if (poll.next != null) {
32+
queue.offer(poll.next);
33+
}
34+
}
35+
return res.next;
36+
}
37+
}

0 commit comments

Comments
 (0)