Skip to content

Commit d773fe8

Browse files
committed
modify code
1 parent e6c3be3 commit d773fe8

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package class05;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
6+
public class Code06_MergeKSortedLists {
7+
8+
public static class ListNode {
9+
public int val;
10+
public ListNode next;
11+
}
12+
13+
public static class ListNodeComparator implements Comparator<ListNode> {
14+
15+
@Override
16+
public int compare(ListNode o1, ListNode o2) {
17+
return o1.val - o2.val;
18+
}
19+
20+
}
21+
22+
public static ListNode mergeKLists(ListNode[] lists) {
23+
if (lists == null) {
24+
return null;
25+
}
26+
PriorityQueue<ListNode> heap = new PriorityQueue<>(new ListNodeComparator());
27+
for (int i = 0; i < lists.length; i++) {
28+
if (lists[i] != null) {
29+
heap.add(lists[i]);
30+
}
31+
}
32+
if (heap.isEmpty()) {
33+
return null;
34+
}
35+
ListNode head = heap.poll();
36+
ListNode pre = head;
37+
if (pre.next != null) {
38+
heap.add(pre.next);
39+
}
40+
while (!heap.isEmpty()) {
41+
ListNode cur = heap.poll();
42+
pre.next = cur;
43+
pre = cur;
44+
if (cur.next != null) {
45+
heap.add(cur.next);
46+
}
47+
}
48+
return head;
49+
}
50+
51+
}

0 commit comments

Comments
 (0)