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;
}
}