Remove Nth Node From End of List

Posted by Bill on March 28, 2023

19. Remove Nth Node From End of List

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

1
2
3
4
5
6
7
8
9
10
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:

Input: head = [1], n = 1
Output: []
Example 3:

Input: head = [1,2], n = 1
Output: [1]

C++ Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ListNode* removeNthFromEnd(ListNode* head, int n) {
  ListNode* ptr = head;
  int len = 0;
  while (ptr != nullptr) {
    len++;
    ptr = ptr->next;
  }
  int index = len - n - 1;
  ListNode *guard = new ListNode();
  guard->next = head;
  ptr = guard;
  int i = -1;
  while (i < index) {
    ptr = ptr->next;
    i++;
  }
  auto removeNode = ptr->next;
  if (removeNode != nullptr) {
    ptr->next = removeNode->next;
  }
  return guard->next;
}