Interview Hot Questions (Merge K Ascending Linked Lists)

Given an array of linked lists, each linked list is already sorted in ascending order.

Please merge all linked lists into one ascending linked list, and return the merged linked list.

Input: lists = [[1,4,5],[1,3,4],[2,6]]
 Output: [1,1,2,3,4,4,5,6]
 Explanation: linked list array as follows:
[
  1->4->5,
  1->3->4,
  2->6
]
Merge them into an ordered linked list to get.
1->1->2->3->4->4->5->6

       This question seems difficult, but it is actually relatively easy to think about. We can maintain a priority minimum queue, and then declare a virtual head node. Each time a minimum node is mounted behind the mounted node. When When the queue is empty, it means that our K ascending lists have been merged

 

public ListNode mergeKLists(ListNode[] lists) {
     if(lists==null||lists.length==0){
         return null;
     }
     //自定义比较器
     PriorityQueue<ListNode> queue=new PriorityQueue<>(new Comparator<ListNode>() {
         @Override
         public int compare(ListNode o1, ListNode o2) {
             return o1.val-o2.val;
         }
     });
     //将K个节点的头结点入队
     for(ListNode node:lists){
         if(node!=null){
           queue.offer(node);
         }
     }
     //创建一个虚拟头结点
     ListNode dummyNode=new ListNode(-1);
     ListNode curNode=dummyNode;
     while(!queue.isEmpty()){
         ListNode cur=queue.poll();
         curNode.next=cur;
         //更新curNode
         curNode=curNode.next;
         //如果当前节点的next不为空,则让下一个节点进行入队
         if(cur.next!=null){
             queue.offer(cur.next);
         }
     }
     return dummyNode.next;
    }

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/132287170