Dec-15-2020, 08:56 PM
The question is
My code:
But I got the error at line 19
Thanks for the hint.
Given the head of a linked list, remove the nth node from the end of the list and return its head.
My code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class ListNode: def __init__( self , val = 0 , next = None ): self .val = val self . next = next class Solution: def removeNthFromEnd( self , head: ListNode, n: int ) - > ListNode: total = 0 temp = head while temp is not None : temp = temp. next total + = 1 k = total - n prev = None curr = head while k > 0 : prev. next = curr curr = curr. next k - = 1 if prev is None : return head. next else : prev. next = curr. next return head list1 = ListNode( 2 ); list1. next = ListNode( 4 ) list1. next . next = ListNode( 3 ) list1. next . next . next = ListNode( 5 ); list1. next . next . next . next = ListNode( 6 ); list1. next . next . next . next . next = ListNode( 4 ) list1. next . next . next . next . next . next = ListNode( 7 ) s = Solution() print (s.removeNthFromEnd(list1, 5 )) |
Quote: File "C:\Code\Leetcode-python\19.py", line 19, in removeNthFromEnd
prev.next = curr
AttributeError: 'NoneType' object has no attribute 'next'
Thanks for the hint.