ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Node slow = head, fast = head
while (fast.next != NULL AND fast.next.next != NULL)
    slow = slow.next
    fast = fast.next.next
end while
Print slow.value
  1. A. 3
  2. B. 4
  3. C. 6
  4. D. 2

Correct answer: A. 3

fast moves 1 → 3 → 5 and then stops because 5 has only one node after it; slow moves 1 → 2 → 3. For an even-length list this test gives the FIRST of the two middle nodes, 3. Testing fast != NULL AND fast.next != NULL instead gives 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic