import java.util.*;

public class Solution {
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        PriorityQueue<ListNode> queue=new PriorityQueue<>((o1,o2)->(o1.val-o2.val));
        for(int i=0;i<lists.size();i++){
            if(lists.get(i)!=null){
                queue.add(lists.get(i));
            }
        }
        ListNode list=new ListNode(-1);
        ListNode cur=list;
        while(!queue.isEmpty()){
            ListNode node=queue.poll();
            list.next=node;
            list=list.next;
            if(node.next!=null){
                queue.offer(node.next);
            }
        }
        return cur.next;
    }
}