[23] 合并 K 个升序链表
from typing import List,Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import heapq
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
pq = []
dummy = ListNode(-1)
p = dummy
for head in lists:
if head:
heapq.heappush(pq,(head.val,id(head),head))
while pq:
node = heapq.heappop(pq)[2]
p.next = node
if node.next:
heapq.heappush(pq,(node.next.val,id(node.next),node.next))
# p指针不断前进
p = p.next
return 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