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?- 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
- B. Nothing – it reverses correctly
- C. It loops forever
- 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
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?
- Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print? python def twosumsorted(a, t)…
- Problem: A ride app must repeatedly add drivers with ratings and remove the highest-rated driver, n = 10⁵ operations. Which data structure…
- Problem: A leaderboard needs: insert a score, delete a score, and 'how many scores are below x?' – all online, 10⁵ operations, scores up…
- Problem: A browser keeps history so that 'back' and 'forward' work like the real buttons, and visiting a new page clears the forward…