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")
问题原因拆解
- toString方法无效:Python没有
toString()方法,对应的是魔法方法__str__,自定义的toString不会被Python打印机制调用,因此默认输出对象内存地址。 - __repr__无限循环:如果你的
__repr__实现中引用了self.next(比如return f"Node({self.data}, {self.next})"),会递归触发后续节点的__repr__,最终导致栈溢出。正确的做法是只描述当前节点,不要关联后续节点。 - 直接访问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
相关产品推荐
相关产品推荐

