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?
- A. Walk with a pointer-to-pointer pp = &head, advance pp = &(*pp)->next k - 1 times, then *pp = (*pp)->next
- B. Walk from the head with p, and free p directly without touching the previous node
- C. Swap the value of node k with its next node and free the next node, which fails for the last node
- 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
- Which realloc pattern does not leak memory or lose the original block if the reallocation fails?
- A dynamic array doubles its capacity whenever it is full. Pushing N = 10^6 values costs about how many element copies in total?
- A function returns a pointer to a node created with malloc inside it. Which description is correct?
- Which statement about calloc(n, size) is guaranteed by the C standard?
- A program calls free(p) and then reads p->v in the next line. What is the correct description?
- A hash chain delete on a singly linked bucket list is written with a pointer-to-pointer. Which description is the advantage?