Dec-15-2020, 08:56 PM
The question is
My code:
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:
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))But I got the error at line 19Quote: 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.
