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.Transfer exercise: apply the lesson to a complete function contract.
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.
head is NULL or owns a finite acyclic heap-node list. Invalid n is a no-op. Free exactly the removed node, preserve all others, and return the possibly changed head.
typedef struct node { int v; struct node *next; } node_t;
node_t *remove_nth(node_t *head, int n) { /* TODO */ return head; }
Losing the head update, leaking the victim, or reading its next field after free.
Empty list; negative/out-of-range index; first/last node; single node.
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.