Skip to content

Latest commit

 

History

History
49 lines (39 loc) · 1.42 KB

File metadata and controls

49 lines (39 loc) · 1.42 KB

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Screen Shot 2021-09-13 at 11 21 48 PM

Screen Shot 2021-09-13 at 11 45 22 PM

/**
 * 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)