# Remove Nth Node From End of List

**Approach:**

We create a dummy node which points to the head of linked list. It is used for help in corner cases like when there is only one node in the list. Now we can use two pointers, fast and slow. We point both the pointers to dummy node. We can move the fast pointer by n nodes first and then move fast and slow pointers together, thereby maintaining the constant gap of n nodes between them. We move the pointers until the fast pointer reaches last node. Now, the slow pointer will be pointing at nth node from the last, since they have a gap of n nodes between them. We will then link the slow pointer’s next to the next of its next node, thus deleting the middle node (required node).

**Solution:**

```
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy=new ListNode();
dummy->next=head;
ListNode* slow=dummy;
ListNode* fast=dummy;
for(int i=0;i<n;i++)
fast=fast->next;
while(fast->next!=NULL){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummy->next;
}
}
```

**Time Complexity:** O(n)

**Space Complexity:** O(1)