Function to delete node gives AttributeError: 'NoneType' object has no attribute 'next'

Viewed 36

This is my code:

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

I get this error:

AttributeError: 'NoneType' object has no attribute 'next'

What is my mistake?

1 Answers

Several issues:

  • When the while loop exits without finding x, then curr will be None and an error occurs when evaluating curr.next. So you should foresee the case where x is not found and not alter anything to the linked list in that case.

  • When x happens to be the head node, then prev will never have received a value, and so prev.next = will raise an error.

  • The code does not foresee that the head of the list might need to change.

Not a problem, but:

  • Since the instance has a head attribute, there should be no need for the function to return the head node. If the caller needs this information, they can read the head attribute.

  • Give meaningful names. dn is cryptic. Name your method delete or deletenode.

Corrected code:

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
Related