为什么循环结束时会这样?node5 不是 NoneType.(遍历链表)



下面的代码。我从概念上理解循环结束是因为最终节点的 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)打印Frinode = node.nextnode设置为None,因为我们从未设置node5next属性,然后while循环终止。

问题是在最后一次迭代中,node被设置为None,因为node5nextNone。您可以通过在遇到这种情况时中断循环来避免这种情况......

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

相关内容

  • 没有找到相关文章

最新更新