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) {
        // write code here
	  // 自定义排序规则
        PriorityQueue<ListNode> pq = new PriorityQueue<>((p1, p2) -> p1.val - p2.val); // (p1, p2) -> {return p1.val - p2.val;}
        for(ListNode x : lists){
            if(x != null)pq.offer(x); // 空链表不能加入优先队列,否则排序比较时出现空指针异常
        }
        while(pq.size() > 1){
            ListNode p1 = pq.poll();
            ListNode p2 = pq.poll();
            ListNode res =  merge(p1, p2);
            pq.offer(res);
        }
        return pq.poll();
    }
  // 合并两个有序链表
    private ListNode merge(ListNode pHead1, ListNode pHead2){
        ListNode res = new ListNode(-1);
        ListNode p1 = pHead1, p2 = pHead2, cur = res;
        while(p1 != null && p2 != null){
            if(p1.val <= p2.val){
                cur.next = p1;
                p1 = p1.next;
            }else{
                cur.next = p2;
                p2 = p2.next;
            }
            cur = cur.next;
        }
        cur.next = p1 == null ? p2 : p1;
        return res.next;
    }
}