Description Link to heading

19.remove-nth-node-from-end-of-list

Solution Link to heading

For convenience, we create a virtual head node pre, pre->next = head.

We will use two pointers fast and slow. First, fast go head for n times, then fast and slow go ahead together. When fast arrives at last node, slow points to the last node of the node we need delete.

Code Link to heading

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