![](/img/trans.png)
[英]AttributeError: 'NoneType' object has no attribute 'next_node'
[英]Function to delete node gives AttributeError: 'NoneType' object has no attribute 'next'
這是我的代碼:
def dn(self,x):
curr = self.head
while curr is not None:
if(curr==x):
break
curr=curr.next
prev= curr
temp = curr.next
prev.next= temp
return self.head
我收到此錯誤:
AttributeError: 'NoneType' object 沒有屬性 'next'
我的錯誤是什么?
幾個問題:
當while
循環退出而沒有找到x
時, curr
將為None
並且在評估curr.next
時會發生錯誤。 因此,您應該預見到未找到x
的情況,並且在這種情況下不要更改鏈表的任何內容。
當x
恰好是頭節點時, prev
將永遠不會收到值,因此prev.next =
將引發錯誤。
該代碼沒有預見到列表的頭部可能需要更改。
不是問題,但是:
由於實例有head
屬性,function應該不需要返回head節點。 如果調用者需要這些信息,他們可以讀取head
屬性。
給出有意義的名字。 dn
是神秘的。 將您的方法命名為delete
或deletenode
。
更正的代碼:
def deletenode(self, x):
prev = None # Initialise
curr = self.head
while curr:
if curr == x:
break
curr = curr.next
prev = curr
else: # curr is None
return self.head # List does not have the value
temp = curr.next
if prev: # It is not the head node that is to be removed
prev.next = temp
else: # The head node is to be removed
self.head = temp
# Don't return anything
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.