Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Reverse a singly linked list (C++):

Problem: Reverse a singly linked list (C++):
Node* prev = nullptr;
while (head) {
    head->next = prev;     // line 3
    prev = head;
    head = head->next;     // line 5
}
return prev;
What goes wrong?
  1. A. After line 3 the original next pointer is lost, so line 5 moves head back to prev and the loop ends after one node; save next in a temporary first
  2. B. Nothing – it reverses correctly
  3. C. It loops forever
  4. D. It crashes on an empty list

Correct answer: A. After line 3 the original next pointer is lost, so line 5 moves head back to prev and the loop ends after one node; save next in a temporary first

head->next was overwritten with prev (nullptr in the first step), so head = head->next makes head null and only the first node is 'reversed'. Store Node* nxt = head->next before line 3, then advance with head = nxt. An empty list is fine (loop never runs).

More Coding Interview Problems questions

Exams that ask this topic