首页 > 解决方案 > 我如何让我的班级打印出任何现在的孩子?

问题描述

所以我对 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"

标签: python

解决方案


您可以__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

推荐阅读