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 -> NULL, head points to node 1
Node prev = NULL, cur = head, nxt
Integer k = 0
while (cur != NULL AND k < 3)
    nxt = cur.next
    cur.next = prev
    prev = cur
    cur = nxt
    k = k + 1
end while
head.next = cur
head = prev
Print the values from head to NULL
  1. A. 3 2 1
  2. B. 5 4 3 2 1
  3. C. 1 4 5
  4. D. 3 2 1 4 5

Correct answer: D. 3 2 1 4 5

The loop reverses the first three nodes (3 → 2 → 1). The old head (node 1) is now last in that block and is reconnected to node 4, so the list reads 3 2 1 4 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic