题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
import java.util.*; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode mergeKLists(ArrayList<ListNode> lists) { if (lists == null || lists.size() < 1) { return null; } int n = lists.size(); if (n == 1) { return lists.get(0); } PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> o1.val - o2.val); for (int i = 0; i < n; i++) { if (lists.get(i) != null) { pq.offer(lists.get(i)); } } ListNode dummy = new ListNode(-1); ListNode tail = dummy; while (!pq.isEmpty()) { ListNode cur = pq.poll(); tail.next = cur; tail = cur; if (cur.next != null) { pq.add(cur.next); } } return dummy.next; } }