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

发布时间:2023年12月28日

[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

文章来源:https://blog.csdn.net/weixin_40293999/article/details/135279383
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。