[23] 合并 K 个升序链表
from typing import List,Optional
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = nextimport heapqclass Solution:def mergeKLists(self, lists: List[ListNode]) -> ListNode:if not lists:return Nonepq = []dummy = ListNode(-1)p = dummyfor head in lists:if head:heapq.heappush(pq,(head.val,id(head),head))while pq:node = heapq.heappop(pq)[2]p.next = nodeif node.next:heapq.heappush(pq,(node.next.val,id(node.next),node.next))# p指针不断前进p = p.nextreturn dummy.next
注意点1
对 head是否为None的判断必须有:
for head in lists:if head:heapq.heappush(pq,(head.val,id(head),head
否则过不了测试用了[None]
while pq:
p.next = node
或者 p.next = ListNode(node.val) 无区别
因为p.next 会被覆盖成小顶堆的最小值,知道没值了,指向None