aboutsummaryrefslogtreecommitdiff
path: root/remove_nth_node.cpp
blob: 38f8a722400966a912e3cb0369e03a86182ee4b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "leetcode.h"

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