-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
32 lines (31 loc) · 867 Bytes
/
MergeKSortedLists.java
File metadata and controls
32 lines (31 loc) · 867 Bytes
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> q = new PriorityQueue<>(Comparator.comparing(a -> a.val));
for (ListNode node : lists) {
if (node != null) {
q.add(node);
}
}
ListNode head = new ListNode();
ListNode pre = head;
ListNode top = null;
while ((top = q.poll()) != null) {
pre.next = top;
if (top.next != null) {
q.add(top.next);
}
pre = pre.next;
}
return head.next;
}
}