LeetCode地址:https://leetcode-cn.com/problems/merge-k-sorted-lists/
1、解题思路
利用小顶堆实现,Java中利用PriorityQueue进行实现,下面是实现的图解
2、实现代码
import java.util.Comparator;
import java.util.PriorityQueue;
//leetcode原题地址:
class Solution{
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;
}
}
//重新实现从小到大的排序(这一步很重要)
public static class ListNodeComparator implements Comparator<ListNode> {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
}
public static ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
// 将所有的Node放进小顶堆
PriorityQueue<ListNode> pq = new PriorityQueue<>(new ListNodeComparator());
for (ListNode listBode : lists) {
if (listBode != null)
pq.add(listBode);
}
// 判断pq是否为空 为空
if (pq.isEmpty()) {
return null;
}
// 将最小值弹出来当做头结点
ListNode head = pq.poll();
// pre当做中间(将头节点记录)
ListNode pre = head;
// 因为头结点弹了出来 所以要把下一个节点放进去
if (pre.next != null) {
pq.add(pre.next);
}
// 按照大小顺序 弹出节点挂在头结点之后 并且将下一个放进去 直到都弹出
while (!pq.isEmpty()) {
ListNode cur = pq.poll();
pre.next = cur;
pre = cur;
if (cur.next != null) {
pq.add(cur.next);
}
}
return head;
}
}