题目:23. 合并K个升序链表
思路:优先队列。
我们把所有的节点放到优先队列里,重写Comparator
方法,按照节点的值排序,这样队列里的节点都是有序的,然后我们按照顺序串起来所有节点即可。
代码:
/**
* 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> queue = new PriorityQueue<>(comparaList);
ListNode fake = new ListNode();
ListNode res = fake;
for (int i = 0; i < lists.length; i++) {
while (lists[i] != null) {
queue.add(lists[i]);
lists[i] = lists[i].next;
}
}
while (!queue.isEmpty()) {
fake.next = queue.poll();
fake = fake.next;
fake.next = null;
}
return res.next;
}
public static Comparator<ListNode> comparaList = new Comparator<ListNode>() {
@Override
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
};
}