The challenge
Remove the nth node from the end and return the new head.
n is one-based. If n ≤ 0 or n exceeds the list length, leave the list unchanged.
Example
[1, 2, 3, 4, 5], n = 2 → [1, 2, 3, 5].
Use the walkthrough below to inspect the input and each state change.
See Remove nth from end, step by step
Follow the pointers. Watch each link change.
A1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 1 | A2 |
| A2 | 2 | A3 |
| A3 | 3 | A4 |
| A4 | 4 | A5 |
| A5 | 5 | null |
Read the input
IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.
Start from the input head pointers.View original input
A: 1 (A1) → 2 (A2) → 3 (A3) → 4 (A4) → 5 (A5); parameters: {"n":2}
Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.
Put it into code
With a dummy head, a gap of n nodes puts slow just before the node to remove.
Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nth(head, n):
if n <= 0:
return head
dummy = Node(next=head)
slow = fast = dummy
for _ in range(n):
fast = fast.next
if fast is None:
return head
while fast.next:
slow, fast = slow.next, fast.next
slow.next = slow.next.next
return dummy.next
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
Node* remove_nth(Node* head, int n) {
if (n <= 0) return head;
Node dummy(0, head);
Node* slow = &dummy;
Node* fast = &dummy;
for (int i = 0; i < n; ++i) {
fast = fast->next;
if (!fast) return head;
}
while (fast->next) {
slow = slow->next;
fast = fast->next;
}
Node* removed = slow->next;
slow->next = removed->next;
delete removed;
return dummy.next;
}