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

Transfer exercise: apply the lesson to a complete function contract.

Input format

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

Output format

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

Constraints

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.

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

Losing the head update, leaking the victim, or reading its next field after free.

Edge cases to handle

Empty list; negative/out-of-range index; first/last node; single node.

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.