ProgrammingVery hard

Which operation removes the k-th node (1-based) from a singly linked list in one pass with a pointer to the previous node, and handles removal of the head safely?

  1. A. Walk with a pointer-to-pointer pp = &head, advance pp = &(*pp)->next k - 1 times, then *pp = (*pp)->next
  2. B. Walk from the head with p, and free p directly without touching the previous node
  3. C. Swap the value of node k with its next node and free the next node, which fails for the last node
  4. D. Copy the list into an array, delete an element, and rebuild the list in O(N^2)

Correct answer: A. Walk with a pointer-to-pointer pp = &head, advance pp = &(*pp)->next k - 1 times, then *pp = (*pp)->next

The pointer-to-pointer walk gives the link to change, so the head needs no special case. The swap trick breaks on the last node, and copying costs O(N^2) when rebuilt naively.

More C Programming questions

Exams that ask this topic