class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nth_from_end(head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head) # dummy node to handle edge cases
slow = dummy
fast = dummy
# Move fast pointer n steps ahead
for _ in range(n):
fast = fast.next
# Move both pointers until fast reaches the end
while fast.next:
slow = slow.next
fast = fast.next
# Remove the nth node from end
slow.next = slow.next.next
return dummy.next
def print_list(head: ListNode):
curr = head
result = []
while curr:
result.append(str(curr.val))
curr = curr.next
print(" -> ".join(result) + " -> null")
# Driver code
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
n = 2
new_head = remove_nth_from_end(head, n)
print_list(new_head)dummy = ListNode(0, head) # dummy node to handle edge cases
Create dummy node to simplify removal especially if head is removed
for _ in range(n):
fast = fast.next
Advance fast pointer n steps ahead to create gap
while fast.next:
slow = slow.next
fast = fast.next
Move slow and fast together until fast reaches last node
slow.next = slow.next.next
Skip the target node by linking slow.next to node after next
Return head of modified list, skipping dummy