class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
你好,我在理解上面的循环时有些困难,AFAIK你需要有一个while循环的条件,所以:
while (stuff) == True:
但上面的代码有:
while current:
这是否与:
相同while current == head:
由于
答案 0 :(得分:7)
while current:
语法的字面意思是while bool(current) == True:
。该值将首先转换为bool,然后与True
进行比较。在python中,每次转换为bool都是True
,除非它是None
,False
,零或空集合。
请参阅truth value testing部分以供参考。
答案 1 :(得分:0)
您的循环可视为
while current is not None:
因为解析器会尝试将current解释为boolean(而None,空列表/ tuple / dict / string以及0计算为False)
答案 2 :(得分:0)
变量current
的值是条件。如果它是真的,循环继续,如果它是假的循环停止。期望在链表中的最后一个元素中,next
将包含一个假值。我假设该值为None
,在这种情况下,循环等效于:
while Current is not None:
相反,如果链接列表使用false
作为结束标记,则相当于:
while Current != false: