import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        ListNode hair = new ListNode(0);
        ListNode pointer = hair;
        PriorityQueue<ListNode> que = new PriorityQueue<>(new Comparator<ListNode>() {
            public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }
        });
        for (ListNode node : lists) {
            if (node != null) {
                que.offer(node);
            }
        }
        while (!que.isEmpty()) {
            ListNode current = que.poll();
            pointer.next = current;
            pointer = pointer.next;
            if (current.next != null) {
                que.offer(current.next);
            }
        }
        return hair.next;
    }
}