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

Python实现Singly Linked List(单链表)运行报错,求问题排查与修复方案

问题定位

代码存在2处核心错误:

  • Node类初始化时next属性赋值错误:你将self.next赋值为传入的data,但单链表节点的next需要初始化为None,用来指向后续节点
  • 类缩进错误:singly_linked_list类现在被缩进成了Node的内部类,无法直接实例化调用,需要调整缩进和Node类平级

修复后的完整代码

class Node:
    # 单链表节点类
    def __init__(self, data):
        self.data = data
        self.next = None # 修改为初始空值

# 调整缩进和Node类平级
class singly_linked_list:
    def __init__(self):
        # 初始化空链表
        self.head = None
        self.tail = None
        self.count = 0
        
    def print_all_item(self):
        # 遍历输出所有节点
        current_item = self.head
        while current_item:
            val = current_item.data
            current_item = current_item.next
            print(val)
            
    def append_item(self, data):
        # 链表尾部追加节点
        node = Node(data)
        if self.tail:
            self.tail.next = node
            self.tail = node
        else:
            self.head = node
            self.tail = node
        self.count += 1

使用你提供的测试代码运行后,即可输出预期结果:

PHP
Python
C#
C++
Java

内容的提问来源于stack exchange,提问作者ARIEL ADHIDEVARA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:15:05