pointers-memory · intermediate · ~25 min
Pointer-to-pointer to unlink without a head special-case.
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;
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.
head — the first node (may be NULL for an empty list). n — a 0-indexed position; may be negative or past the end.
Returns the new head pointer. The removed node is freed. If n is out of range (negative, or >= list length), the list is unchanged.
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)
n == 0 removes the first node (head changes).n beyond the list, or negative: no-op, return 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 (may be NULL) and a 0-indexed position n (may be out of range).
The new head pointer; the removed node is freed.
One pass. Don't leak. Out-of-range n leaves the list unchanged.
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.