class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy_head = new ListNode(0, head);
ListNode *fast = dummy_head;
ListNode *slow = dummy_head;
n++;
while(n-- && fast != nullptr)
{
fast = fast->next;
}
while(fast != nullptr)
{
fast = fast->next;
slow = slow->next;
}
ListNode *temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummy_head->next;
}
};
Python:
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(0, head)
fast = dummy_head
slow = dummy_head
n += 1
while n and fast != None:
fast = fast.next
n -= 1
while fast != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next