Time Cost

14min49s

Implementation

Quick-Slow Pointers. When the quick pointer hits the boundary then stops.

Code

  • Solution
    class Solution {
    public:
      ListNode* removeNthFromEnd(ListNode* head, int n) {
          ListNode dummy(0);
          dummy.next = head;
    
          ListNode* fast = &dummy;
          ListNode* slow = &dummy;
    
          for (int i = 0; i < n + 1; i++) fast = fast->next;
    
          while (fast) {
              fast = fast->next;
              slow = slow->next;
          }
    
          ListNode* toRemove = slow->next;
          slow->next = toRemove->next;
          return dummy.next;
      }
    };