You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现middleNode函数报错:'list' object has no attribute 'next'

问题分析与解决

错误根源

你遇到的'list' object has no attribute 'next'错误,核心原因是传入函数的head是普通Python列表,而非你定义的ListNode类实例。列表本身没有next属性,所以函数执行head.next时直接报错。

除此之外,代码里还有两处关键问题:

  • temp=ListNode(head)是错误的初始化方式:你把整个列表(或链表头)传给了ListNode的val参数,导致temp并非链表的头节点,而是一个val为列表的单个节点。
  • num=(num/2)+1使用了浮点数除法,当链表长度为偶数时,num会变成浮点数,后续循环判断num > 1会出现逻辑问题。

修正后的完整代码

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 辅助函数:将普通列表转换为链表结构
def list_to_linked_list(arr):
    if not arr:
        return None
    head = ListNode(arr[0])
    current = head
    for num in arr[1:]:
        current.next = ListNode(num)
        current = current.next
    return head

def middleNode(head: ListNode) -> ListNode:
    # 处理空链表或单个节点的情况
    if not head or not head.next:
        return head
    
    num = 0
    temp = head  # 直接指向链表头节点,而非新建节点
    # 统计链表长度
    while temp:
        num += 1
        temp = temp.next
    
    # 计算中间节点的位置(整数除法)
    num = num // 2 + 1
    # 遍历到中间节点
    while num > 1:
        head = head.next
        num -= 1
    return head

# 测试:先把列表转成链表,再调用函数
head_list = [1,2,3,4,5]
linked_head = list_to_linked_list(head_list)
result = middleNode(linked_head)

# 打印结果验证
current = result
while current:
    print(current.val, end=" ")

额外优化:快慢指针法

找链表中间节点更高效的方法是快慢指针,无需统计长度,一次遍历就能完成:

def middleNode(head: ListNode) -> ListNode:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

这个方法里,快指针每次走两步,慢指针每次走一步,当快指针走到末尾时,慢指针正好在中间节点位置,时间复杂度O(n),空间复杂度O(1),比统计长度的方法更优。

内容的提问来源于stack exchange,提问作者Luis Valencia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:45:42