python - 我在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”对象没有“下一个”属性。
请帮助我了解这两者的不同之处。
解决方案
while self.head
是一个永远不会改变的条件,因为self.head
在循环中没有改变(也不应该)。所以这意味着,如果它曾经为真,它将永远为真。
您可能会错误地认为,当对 进行新分配时current
,该分配也适用于self.head
,但事实并非如此。它们是两个独立的引用(一个属性和一个变量),恰好在循环开始时引用了同一个节点。但是如果current
get 引用不同的节点,这不会影响self.head
引用的内容。
将其与这种琐碎的情况进行比较:
a = b = 1
a = 2
print(b) # still 1.
同样的原则也适用于self.head
和current
。分配到current
不会self.head
影响.
现在例外:循环的主体将新值分配给current
:
current=current.next
在某些时候current
将引用列表的最后一个节点,然后current.next
是None
. 因此,当上述分配再次发生时,current
将是None
. 但是循环没有结束,因为self.head
没有改变(仍然引用第一个节点),所以下一次迭代将再次计算current.next
,但这会触发错误,因为None
没有属性next
。
结论,您的条件应该是在iswhile
时使循环退出的东西。current
None
推荐阅读
- kotlin - 在类扩展函数中使用类变量
- php - PHP PDO 使用 fetchObject 创建一个类的对象
- react-native - React Native:将 Pan Responder 事件从视图传播到内部滚动视图
- optimization - 使用选项时的 Hyperas 语法问题
- c# - ASP.NET MVC Check 在 Global.asax 中是可移动的
- google-app-engine - Google App Engine Python 3.7 中的多项服务
- python - 如何使用 Google Cloud API 和 Python 触发流式语音识别
- python - 当包装器具有实例变量时键入类装饰器
- css - 通过 CSS 将自定义字体添加到 Wordpress 主题
- postgresql - 如何通过终端在 psql 中保存查询