-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
44 lines (36 loc) · 948 Bytes
/
Copy pathMergeKSortedLists.java
File metadata and controls
44 lines (36 loc) · 948 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
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> nodes = new PriorityQueue<>(Comparator.comparing(l -> l.val));
ListNode dummy = null;
for (ListNode listNode : lists) {
dummy = listNode;
while (dummy != null) {
nodes.add(dummy);
dummy = dummy.next;
}
}
ListNode head = nodes.poll();
dummy = head;
while (!nodes.isEmpty()) {
dummy.next = nodes.poll();
dummy = dummy.next;
}
dummy.next = null;
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val; this.next = next;
}
}