首页 > 解决方案 > 我在python的链表中遇到问题

问题描述

我正在创建一个链表并添加一个函数来获取给定位置的元素。

我在下面附上了我的代码。

在我的代码中current = self.head。这里current是指派的self.head。那么这两者不都一样吗?在while我使用while current代码的循环中没有任何错误:

def get_position(self, position):
    current = self.head
    counter =0
    while current:
        counter+=1
        current=current.next
    print("total elements:",counter)

但是如果我使用while self.head我会得到一个错误:

def get_position(self, position):
    current = self.head
    counter =0
    while self.head:
        counter+=1
        current=current.next
    print("total elements:",counter)

AttributeError:“NoneType”对象没有“下一个”属性。

在第二张图片中,我使用了 self.head。 在这里我得到了错误

请帮助我了解这两者的不同之处。

标签: python

解决方案


while self.head是一个永远不会改变的条件,因为self.head在循环中没有改变(也不应该)。所以这意味着,如果它曾经为真,它将永远为真。

您可能会错误地认为,当对 进行新分配时current,该分配适用于self.head,但事实并非如此。它们是两个独立的引用(一个属性和一个变量),恰好在循环开始时引用了同一个节点。但是如果currentget 引用不同的节点,这不会影响self.head引用的内容。

将其与这种琐碎的情况进行比较:

a = b = 1
a = 2 
print(b)  # still 1.

同样的原则也适用于self.headcurrent分配current不会self.head影响.

现在例外:循环的主体将新值分配给current

current=current.next

在某些时候current将引用列表的最后一个节点,然后current.nextNone. 因此,当上述分配再次发生时,current将是None. 但是循环没有结束,因为self.head没有改变(仍然引用第一个节点),所以下一次迭代将再次计算current.next,但这会触发错误,因为None没有属性next

结论,您的条件应该是在iswhile时使循环退出的东西。currentNone


推荐阅读