這道題注意 priorityqueue里面不能放null, 所以每次入堆的時候要判斷是不是null. 也就是下面這幾個if語句:
for (ListNode list : lists){
if (list != null){
pq.offer(list);
}
}
以及
while (!pq.isEmpty()){
ListNode top = pq.poll();
curt.next = top;
if (top.next != null){
pq.offer(top.next);
}
curt = curt.next;
curt.next = null;
}
其實就是一開始集體入最小堆的時候要檢查是不是有空鏈表糟趾,然后就是把鏈表的當前節(jié)點加入答案里后归榕,還要把它的next放入最小堆,這時候也要檢查curt.next是否為空。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0){
return null;
}
int k = lists.length;
ListNode dummy = new ListNode(0);
ListNode curt = dummy;
PriorityQueue<ListNode> pq = new PriorityQueue<>(k, cmp);
for (ListNode list : lists){
if (list != null){
pq.offer(list);
}
}
while (!pq.isEmpty()){
ListNode top = pq.poll();
curt.next = top;
if (top.next != null){
pq.offer(top.next);
}
curt = curt.next;
curt.next = null;
}
return dummy.next;
}
private Comparator<ListNode> cmp = new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2){
return l1.val - l2.val;
}
};
}