23. 合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue queue = new PriorityQueue<>(new Comparator() {
@Override
public int compare(ListNode o1, ListNode o2) {
return Integer.compare(o1.val, o2.val);
}
});
ListNode head = new ListNode(), tail = head;
for (ListNode listNode : lists) {
if (listNode != null) {
queue.offer(listNode);
}
}
while (!queue.isEmpty()) {
ListNode poll = queue.poll();
tail.next = poll;
tail = poll;
if (poll.next != null) {
queue.offer(poll.next);
}
}
return head.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}