【算法刷题】python刷题--合并链表

23 合并 K 个升序链表

python 复制代码
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

相关推荐
eybk4 小时前
写一个可以编制pdf文件的python程序
开发语言·python·pdf
卷无止境4 小时前
从Python的cryptography库出发,从零开始理解密码学,到构建零信任网络
后端·python
YFJ_mily4 小时前
**Python 实战:写一个论文 PDF 投稿自检工具|附 IPAT 2026 智能光子学会议征稿信息
人工智能·python·pdf·量子计算·论文投稿·智能光子学
三川6984 小时前
Tkinter库的学习记录05-文本框Entry
python
cui_ruicheng4 小时前
Python从入门到实战(八):封装、多态与抽象类
开发语言·python
GEO_ai_zhijian5 小时前
饮料生产线质量检测系统哪家好
大数据·人工智能·python
精神底层5 小时前
拒绝 UI 卡死!我用 CSnakes 实时拦截 Python 训练流,在 WPF 中重构了 ScottPlot 5 高性能 AI 看板
python·ui·wpf
尼恩久5 小时前
记录xls表格提取信息
python
工艺资源5 小时前
外贸工艺品设计参考平台众多,哪家专业值得了解
人工智能·python