public class MergeSortList { public static class ListNode{ public int val; public ListNode next; } public static class ListNodeComparator implements Comparator<ListNode>{ @Override public int compare(ListNode o1, ListNode o2) { return o1.val- o2.val; } } public static ListNode mergeKList(ListNode[] listNodes){ if (listNodes==null){ return null; } PriorityQueue<ListNode> heap = new PriorityQueue<>(new ListNodeComparator()); for (int i = 0; i < listNodes.length; i++) { if (listNodes[i]!=null){ heap.add(listNodes[i]); } } if (heap.isEmpty()){ return null; } ListNode head = heap.poll(); ListNode pre=head; if (pre.next!=null){ heap.add(pre.next); } while (!heap.isEmpty()){ ListNode cur=heap.poll(); pre.next=cur; pre=cur; if (cur.next != null){ heap.add(cur.next); } } return head; } }
合并k个升序链表
最新推荐文章于 2024-07-01 14:01:45 发布