【算法刷题】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

相关推荐
aaaameliaaa1 小时前
字符函数和字符串函数
c语言·笔记·算法
笨鸟先飞,勤能补拙2 小时前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
城管不管2 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
长和信泰光伏储能3 小时前
京津冀光伏发电:绿色能源的未来之路
python·能源
月疯3 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡3 小时前
算法日记 - Day3
java·开发语言·算法
浦信仿真大讲堂3 小时前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
白白白小纯3 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang3 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9853 小时前
高进度算法模板速记(待完善)
java·前端·算法