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

Python单链表节点内容打印失败问题求助

解决单链表节点内容打印问题

先给出能正确打印节点数据的代码实现,核心是正确定义Python的魔法方法:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    # 定义__str__方法,返回节点数据的字符串形式
    def __str__(self):
        return str(self.data)

    # 可选:定义安全的__repr__,避免无限循环
    def __repr__(self):
        return f"Node({self.data})"

class LinkedList:
    def __init__(self):
        self.head = None

    def add_node(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    # 遍历打印整个链表
    def print_list(self):
        current = self.head
        result = []
        while current:
            result.append(str(current))
            current = current.next
        print(" -> ".join(result) + " -> None")

问题原因拆解

  1. toString方法无效:Python没有toString()方法,对应的是魔法方法__str__,自定义的toString不会被Python打印机制调用,因此默认输出对象内存地址。
  2. __repr__无限循环:如果你的__repr__实现中引用了self.next(比如return f"Node({self.data}, {self.next})"),会递归触发后续节点的__repr__,最终导致栈溢出。正确的做法是只描述当前节点,不要关联后续节点。
  3. 直接访问data却输出内存地址:如果你的代码是print(node)而非print(node.data),必须通过__str__告诉Python如何将节点对象转为字符串,否则会输出默认的对象标识信息。

测试效果

ll = LinkedList()
ll.add_node("Mon")
ll.add_node("Tues")
ll.add_node("Wed")

ll.print_list()
# 输出:Mon -> Tues -> Wed -> None

# 单独打印单个节点
print(ll.head)          # 输出:Mon
print(ll.head.next)     # 输出:Tues

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:37:20