leetcode 23. Merge k Sorted Lists

I saw in a blog that leetcode 23 is the hardest Linked List problem in leetcode. But I don't think it's that hard.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int N = lists.length;
        if (N == 0) return null;
        ListNode head = new ListNode(0);
        ListNode ptr =head;
        PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(
            (n1, n2) -> n1.val - n2.val);
        for (ListNode node: lists) {
            if (node != null) {
                q.add(node);
            }
        }
        while (!q.isEmpty()) {
            ListNode n = q.poll();
            ptr.next = n;
            ptr = ptr.next;
            n = n.next;
            if (n != null) {
                q.add(n);
            }
        }
        return head.next;
    }
}
posted on 2019-04-15 22:58  王 帅  阅读(115)  评论(0编辑  收藏  举报