pointers-memory · intermediate · ~25 min

Remove the n-th node from a linked list

Pointer-to-pointer to unlink without a head special-case.

Challenge

Remove one node from a singly-linked list by its position, free it, and return the (possibly new) head. Using a pointer-to-pointer lets you handle removing the first node with the same code as any other.

The list node type is:

typedef struct node { int v; struct node *next; } node_t;

Task

Implement node_t *remove_nth(node_t *head, int n) that unlinks the 0-indexed n-th node, frees it, and returns the head of the resulting list. No main — the grader builds the list and calls it.

Input

head — the first node (may be NULL for an empty list). n — a 0-indexed position; may be negative or past the end.

Output

Returns the new head pointer. The removed node is freed. If n is out of range (negative, or >= list length), the list is unchanged.

Example

list 1 -> 2 -> 3 -> 4,  remove_nth(head, 1)   ->   1 -> 3 -> 4
list 1 -> 3 -> 4,        remove_nth(head, 0)   ->   3 -> 4   (head changed)
list 3 -> 4,             remove_nth(head, 5)   ->   3 -> 4   (no-op)

Edge cases

  • n == 0 removes the first node (head changes).
  • n beyond the list, or negative: no-op, return head unchanged.
  • NULL head: return NULL.

Rules

  • Make exactly one pass; do not leak the removed node.

Why this matters

Removing a node from a singly-linked list is the canonical pointer-to-pointer exercise. Done right, you handle 'remove head' and 'remove middle' with the same code — no special cases.

Input format

head (may be NULL) and a 0-indexed position n (may be out of range).

Output format

The new head pointer; the removed node is freed.

Constraints

One pass. Don't leak. Out-of-range n leaves the list unchanged.

Starter code

typedef struct node { int v; struct node *next; } node_t;
node_t *remove_nth(node_t *head, int n) { /* TODO */ return head; }

Common mistakes

Forgetting to update the head when removing the first node. Leaking the removed node (forgot free). Off-by-one on n.

Edge cases to handle

n == 0 (remove head). n past the end (no-op, return head unchanged). Empty list (return NULL).

Complexity

O(n) where n is the index (worst case: full traversal).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.