Python如何实现LinkedList类打印其所有关联的子节点值?
调整后的实现方案
你不需要保留原来有问题的getNext方法,直接在__repr__内置方法里遍历所有后续子节点收集值即可,完整修改代码如下:
class LinkedList: def __init__(self, value): self.value = value self.next = None def __repr__(self): # 遍历收集所有子节点的value child_values = [] current_node = self.next while current_node: child_values.append(str(current_node.value)) current_node = current_node.next # 按要求格式拼接输出内容 return "Current value is: {}. Here are the children links: {}".format( self.value, " -> ".join(child_values) ) one = LinkedList(10) one.next = LinkedList(3) one.next.next = LinkedList(4) one.next.next.next = LinkedList(5)
效果验证
执行print(one)后,输出结果完全符合你的预期:
Current value is: 10. Here are the children links: 3 -> 4 -> 5
逻辑说明
- 遍历从当前节点的
next属性开始,不会重复统计当前节点自身的value - 用列表暂存所有子节点值,最后通过
join方法拼接,自动适配子节点数量为0的场景,不会抛出异常 - 不需要额外编写辅助get方法,减少冗余代码
内容的提问来源于stack exchange,提问作者Sergio Bost
相关产品推荐
相关产品推荐

