小bug in23. Merge k Sorted Lists

这道题注意 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;
        }        

其实就是一开始集体入最小堆的时候要检查是不是有空链表,然后就是把链表的当前节点加入答案里后,还要把它的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;
        }
    };
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/9f6685f120a4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞