- #1
member 428835
Hi PF!
I am looking at the following code
Can anyone tell me what the first 4 lines are doing? Also, when I execute this code I get the error
Anyone know what's happening?
I am looking at the following code
Python:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
# Two pointers - fast and slow
slow = head
fast = head
# Move fast pointer n steps ahead
for i in range(0, n):
if fast.next is None:
# If n is equal to the number of nodes, delete the head node
if i == n - 1:
head = head.next
return head
fast = fast.next
# Loop until fast node reaches to the end
# Now we will move both slow and fast pointers
while fast.next is not None:
slow = slow.next
fast = fast.next
# Delink the nth node from last
if slow.next is not None:
slow.next = slow.next.next
return head
if __name__ == "__main__" :
head = [1,2,3,4,5]
n = 2
print(removeNthFromEnd(head,n))
Code:
Traceback (most recent call last):
File "a19_removeNthNode.py", line 32, in <module>
print(removeNthFromEnd(head,n))
File "a19_removeNthNode.py", line 13, in removeNthFromEnd
if fast.next is None:
AttributeError: 'list' object has no attribute 'next'