我不明白為什么在我的代碼的第 31 行中,它需要while(temp.next):代替 while(temp):Can有人請幫我理解嗎?我是新的和困惑的。這是我的鏈接串列的代碼:
class Node():
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def printlist(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def append(self, new_data):
new_node = Node(new_data)
if self.head == None:
self.head = new_node
else:
temp = self.head
#if I replace the following line with "while(temp):" instead of
#"while(temp.next)"it will not work. Why?
while(temp.next):
temp = temp.next
temp.next = new_node
mylist = LinkedList()
mylist.head = Node(1)
mylist.append(2)
mylist.printlist()
uj5u.com熱心網友回復:
while (temp)將確保在回圈退出temp時是 falsy( ) 。但隨后該回圈下面的陳述句將失敗:None
temp.next = new_node
...因為沒有next屬性 when tempis None。
此while回圈的目標是找到最后一個節點。最后一個節點的顯著特點是它的next屬性是None,從而說明while情況。只要這個節點還有后繼者,就不是最后一個節點,我們應該往前走。這就是這個回圈正在做的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436769.html
上一篇:如何為自定義類實作迭代器?
