LeetCode 23. 合并K个升序链表
思路
使用队列将每个链表元素放入,每次获取最小的元素加入到链表中
实现代码
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> heap = new PriorityQueue<>(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
for (ListNode listNode : lists){
if(listNode!=null) heap.offer(listNode);
}
while (!heap.isEmpty()){
ListNode node = heap.poll();
tail = tail.next = node;
if(node.next !=null) heap.offer(node.next);
}
return dummy.next;
}
}