python - 我如何让我的班级打印出任何现在的孩子?
问题描述
所以我对 python 还很陌生,我只是在创建链接列表来感受这种语言。我如何让父母 LL 打印出任何子链接?我被困在当前的实现中。
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def getNext(self): #faulty method
currentNode = self
if self.next is not None:
currentNode = next
return next.value
def __repr__(self):
return "Current value is: {}. Here are the children links: ".format(self.value)
## How would I print out each child link?
one = LinkedList(10)
one.next = LinkedList(3)
one.next.next = LinkedList(4)
one.next.next.next = LinkedList(5)
**Edit添加了将多个子添加到LL的代码,希望能够打印出父类中的所有子链接
print(one)
在这种情况下,我希望阅读:
"Current value is: 10. Here are the children links: 3 -> 4 -> 5"
解决方案
您可以__repr__
递归执行:
def __repr__(self):
return "Current value is: {}. Here are the children links:\n{}".format(self.value, self.next)
Current value is: 10. Here are the children links:
Current value is: 3. Here are the children links:
None
对于多个链接:
lls = [
LinkedList(10),
LinkedList(3),
LinkedList(78),
LinkedList(-56),
LinkedList(5),
]
lls[0].next = lls[1]
lls[1].next = lls[2]
lls[2].next = lls[3]
lls[3].next = lls[4]
print(lls[0])
Current value is: 10. Here are the children links:
Current value is: 3. Here are the children links:
Current value is: 78. Here are the children links:
Current value is: -56. Here are the children links:
Current value is: 5. Here are the children links:
None
推荐阅读
- ios - Xamarin iOS 无法从 iCloud 获取文件
- reactjs - 如何在反应中删除从地图创建的特定项目?
- azure-devops - DBT(数据构建工具)- 在 Azure DevOps 中创建 CI/CD 管道
- flutter - Flutter 安全存储测试
- c++ - 第 K 个缺失的正整数
- multithreading - 另一个线程中的 or-tools 给出了奇怪的解决方案 java
- docker - 来自守护程序的错误响应:在节点加入之前达到超时
- python - 一个元素的查找索引在列表中多次出现
- node.js - Node Js writeFile在循环许多Base64数据时总是返回0字节
- python - 计算每个系列 Pandas DataFrame 中的特定单词