首页 > 解决方案 > while 循环如何处理类属性

问题描述

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

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

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        # Move to the tail (the last node)
        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)
        return

我对 while 循环语句在这种情况下的工作方式有点困惑。只要条件为真,While 循环就可以工作。我不确定在这种情况下while循环条件将如何返回真或假,有人可以解释一下。谢谢!

标签: pythondata-structureslinked-list

解决方案


node.next评估为一个值,然后将该值评估为布尔值。

具体来说, ifnode.next = Nonebool(None) == False循环中断。否则bool(<Node object>) == True,循环继续。


推荐阅读