Home > Blockchain >  'NoneType' object has no attribute 'next' Error Code appears when Removing Nth N
'NoneType' object has no attribute 'next' Error Code appears when Removing Nth N

Time:11-08

Right Now I'm trying my first medium leetcode problem for the first time (Remove Nth Node From End of List) and I'm pretty confident that the code I have should work with it. But for some reason when I it runs, my while-loop for A.Next gives the error:

NoneType' object has no attribute 'next'
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        a = head
        b = head
        c = head

        i = 0
        while i < n - 1:
            c = c.next
            i  = 1

        while c.next != None:
            b = b.next
            c = c.next

        while a.next != b:
            a = a.next
            
        a.next = b.next
        b = None
    
        return head

It doesn't make sense as to why its not running because I defined my a variable to equal the head which should then also have access to a.next because again, its connected to the head. The while c.next != None: loop works fine without any issues so I don't understand whats causing the issue for my a variable.

CodePudding user response:

head is Optional, which means that it could be None when it is passed to the function. You should check if head is None first before assigning a, b, and c.

CodePudding user response:

Here is what's going on. Your while loop checks a.next != b, which will never be true, hence a becomes equal to None eventually and the check a.next when a is None is failing with error mentioned above. This has nothing to do with linked list logic, it's simply how python compare things.

Your while loop

 while a.next != b: a = a.next

should be changed to

while a.next is not b: a = a.next

know the difference between != and is not, it's extremely important if you want to continue coding in python.

Python != operation vs "is not"

  • Related