import java.util.*;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists == null || lists.size() < 1) {
            return null;
        }
        int n = lists.size();
        if (n == 1) {
            return lists.get(0);
        }
        PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
        for (int i = 0; i < n; i++) {
            if (lists.get(i) != null) {
                pq.offer(lists.get(i)); 
            }
        }
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        while (!pq.isEmpty()) {
            ListNode cur = pq.poll();
            tail.next = cur;
            tail = cur;
            if (cur.next != null) {
                pq.offer(cur.next);
            }
        }
        tail.next = null;
        return dummy.next;
    }
}