Given the head of a linked list, remove the nth node from the end of the list and return its head.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// dummy node to handle edge cases (like deleting head)
ListNode dummy(0);
dummy.next = head;
ListNode* fast = &dummy;
ListNode* slow = &dummy;
// fast moves n steps ahead
for (int i = 0; i < n; i++) {
fast = fast->next;
}
// move both pointers until fast reaches the end
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
// delete the nth node from end
slow->next = slow->next->next;
return dummy.next;
}
};
Time complexity: O(n)
Space Complexity: O(1)

