题目链接

思路

使用优先队列,先把每个链表的头加入队列。然后每次出队列,都把出来的节点向后移动,直到尾。

代码

  1. import java.util.*
  2. import kotlin.Comparator
  3. class Solution {
  4. fun mergeKLists(lists: Array<ListNode?>): ListNode? {
  5. val queue = PriorityQueue<ListNode>(Comparator<ListNode>{ o1, o2->
  6. o1.`val` - o2.`val`
  7. })
  8. if (lists.isEmpty()) return null
  9. for (i in lists.indices) {
  10. if (lists[i] != null) queue.add(lists[i])
  11. lists[i] = lists[i]?.next
  12. }
  13. val head = ListNode(0)
  14. var curr = head
  15. while (queue.isNotEmpty()) {
  16. val nowNode = queue.poll()
  17. curr.next = nowNode
  18. curr = curr.next!!
  19. if (nowNode.next != null) {
  20. queue.add(nowNode.next)
  21. }
  22. }
  23. return head.next
  24. }
  25. }