ProgrammingVery hard

A recursive function removes all nodes equal to x from a singly linked list and returns the new head. Which return statement is the right one for the recursive call?

  1. A. return n->next; always, whether or not n->v equals x
  2. B. n->next = remove_all(n->next, x); return n; (after freeing n when n->v == x, returning n->next)
  3. C. n->next = NULL; return n;
  4. D. return remove_all(n, x); to restart from the same node

Correct answer: B. n->next = remove_all(n->next, x); return n; (after freeing n when n->v == x, returning n->next)

When the node matches, the result is the rest of the list. Otherwise the node stays and its next link is updated. The other forms drop nodes that should remain or loop forever.

More C Programming questions

Exams that ask this topic