I am currently working on a LeetCode problem called Remove Nth Node From End of List. In it I am getting a 'NoneType' Error has no object next error when trying to access a variable equal to the head. The logic may be wrong but I am unsure why I would get an error on this specific variable(seeing as I already checked to see if the head or head.next is None). The " while runner.next is not None:" line is giving me an error. I don;t necessarily need help with the problem as much as why this error is coming about. Thanks! Small Edit. The code runs fine for most sample cases but the one where this error is prevalent is where the list looks like 1 -> 2 - >None(1 is the head).
if not head:
return
if head.next == None:
return
count = 0
walker = head
runner = head
if not walker or not runner:
return
while runner.next is not None:
while(count < n):
runner = runner.next
count = count 1
walker = walker.next
runner = runner.next
walker.next = walker.next.next
return head
CodePudding user response:
On the sample case which you provided, the runner.next property cannot be accessed because runner is None. Your inner while loop iterates at least once if n > 0, progressing runner down the linked list, and then runner is progressed once more at the end of the outer loop. This leaves runner equal to None. Thus when the while loop attempts to check the condition, it attempts to access runner.next and gives you your error. You may wish to update your condition to check that runner is also not None.
