leetcode第23题合并k个升序链表
这个题的逻辑类似于合并两个有序链表,难点在于如何快速得到k个节点中的最小链表,结果接到链表上,这里我们就需要用到优先二叉堆这种数据结构,吧链表的节点放在一个最小堆中,就可以每次获得k个节点中的最小节点.
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0){
return null;
}
//需要用到优先队列
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) {
return -1;
} else if (o1.val == o2.val) {
return 0;
} else {
return 1;
}
}
});
//定义虚拟指针节点内
ListNode dummy = new ListNode(0);
ListNode p = dummy;
for (ListNode head : lists) {
if (head != null) {
queue.add(head);
}
}
while (!queue.isEmpty()) {
ListNode poll = queue.poll();
p.next = poll;
if (poll.next != null) {
queue.add(poll.next);
}
p = p.next;
}
return dummy.next;
}
}