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

Given typedef struct node { int v; struct node *next; } node_t;, implement node_t *remove_nth(node_t *head, int n) that removes the 0-indexed n-th node and returns the new head. Frees the removed node. If n is out of range, returns head unchanged.

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 pointer (may be NULL), 0-indexed n.

Output format

New head pointer.

Constraints

One pass. Don't leak.

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.