Pointers & Memory

Answer & solution
Answer: D (no official key was published)
At loop exit p points to the last node and q to its predecessor. First set q->next=NULL to detach p, then p->next=head to link p before the old first node, and finally head=p. This is option D. Updating head before p->next would lose the old head and can create a self-loop; the early return already handles lists shorter than two nodes.
For A→B→C, the loop ends with p=C and q=B. Detach B→C, point C→A and set head=C, obtaining C→A→B→NULL. Choice A only clears the local variable q and leaves B linked to C, producing a cycle. Choice B makes C point to itself. Choice C loses the old head connection by linking the last node to its predecessor instead.