下面的代码。我从概念上理解循环结束是因为最终节点的 self.next =None
,但我们正在检查该node != None
,并且type(node5)
返回__main__.LinkedListNode
,这不是None
。那么node != None
如何返回False
,结束while循环呢?
class LinkedListNode():
def __init__(self,value):
self.value = value
self.next = None #This is the next point, is initially None
def traverseList(self):
node = self #Start at the Head Node
while node != None:
print(node.value) #Access the node value
node = node.next #Move to the next link in the list
#Create nodes for list
node1 = LinkedListNode('Mon')
node2 = LinkedListNode('Tues')
node3 = LinkedListNode('Wed')
node4 = LinkedListNode('Thurs')
node5 = LinkedListNode('Fri')
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node1.traverseList()
type(node5)
你没有检查是否type(node5) = None
,你的 while 循环检查是否node != None
。
在最后一次迭代中,node
持有node5
,所以print(node.value)
打印Fri
,node = node.next
node
设置为None
,因为我们从未设置node5
的next
属性,然后while循环终止。
问题是在最后一次迭代中,node
被设置为None
,因为node5
next
None
。您可以通过在遇到这种情况时中断循环来避免这种情况......
def traverseList(self):
node = self #Start at the Head Node
while node != None:
print(node.value) #Access the node value
if node.next is None:
break
else:
node = node.next #Move to the next link in the list