/*
合并两个升序链表:直接比较未合并的两个链表头结点即可;
合并K个升序链表:需要比较K个节点,找出最小值,用优先队列,Java默认优先队列为最小堆。
*/
/**
* 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) {
ListNode head = new ListNode(-1), end = head;
PriorityQueue<ListNode> priorityQueue = new PriorityQueue<ListNode>(((o1, o2) -> o1.val - o2.val));
for (ListNode list : lists) {
if (list != null) priorityQueue.add(list);
}
while (!priorityQueue.isEmpty()) {
ListNode node = priorityQueue.poll();
ListNode node1 = new ListNode(node.val);
end.next = node1;
end = node1;
if (node.next != null) priorityQueue.add(node.next);
}
return head.next;
}
}