思路
使用优先队列,先把每个链表的头加入队列。然后每次出队列,都把出来的节点向后移动,直到尾。
代码
import java.util.*import kotlin.Comparatorclass Solution {fun mergeKLists(lists: Array<ListNode?>): ListNode? {val queue = PriorityQueue<ListNode>(Comparator<ListNode>{ o1, o2->o1.`val` - o2.`val`})if (lists.isEmpty()) return nullfor (i in lists.indices) {if (lists[i] != null) queue.add(lists[i])lists[i] = lists[i]?.next}val head = ListNode(0)var curr = headwhile (queue.isNotEmpty()) {val nowNode = queue.poll()curr.next = nowNodecurr = curr.next!!if (nowNode.next != null) {queue.add(nowNode.next)}}return head.next}}
