簡體   English   中英

Function 刪除節點給出 AttributeError: 'NoneType' object 沒有屬性 'next'

[英]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是神秘的。 將您的方法命名為deletedeletenode

更正的代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM