pointers-memory · intermediate · ~25 min
Pointer-to-pointer to unlink without a head special-case.
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.
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.
Head pointer (may be NULL), 0-indexed n.
New head pointer.
One pass. Don't leak.
typedef struct node { int v; struct node *next; } node_t;
node_t *remove_nth(node_t *head, int n) { /* TODO */ return head; }
Forgetting to update the head when removing the first node. Leaking the removed node (forgot free). Off-by-one on n.
n == 0 (remove head). n past the end (no-op, return head unchanged). Empty list (return NULL).
O(n) where n is the index (worst case: full traversal).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.