题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
import java.util.*; //Definition for singly-linked list. class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { //小根堆 /* public static class MyComp implements Comparator { @Override public int compare(ListNode o1, ListNode o2) { return o1.val - o2.val; } }*/ public ListNode mergeKLists(ArrayList lists) { //找出头节点 PriorityQueue heap=new PriorityQueue((a,b)->a.val-b.val); for(ListNode cur:lists){ if(cur!=null){ heap.add(cur); } } if(heap.isEmpty()){ return null; } ListNode head=heap.poll(); if(head.next!=null){ heap.add(head.next); } ListNode cur=head; while(!heap.isEmpty()){ ListNode temp=heap.peek(); cur.next=heap.poll(); cur=cur.next; if(temp.next!=null){ heap.add(temp.next); } } return head; } }