ProgrammingHardAmazon OA · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Queue q = {1, 2, 3, 4, 5}
Integer k = 3
Stack st = empty
for (each i from 1 to k) push(st, dequeue(q))
while (st not empty) enqueue(q, pop(st))
for (each i from 1 to size(q) - k) enqueue(q, dequeue(q))
Print the queue from front to back
  1. A. 4 5 3 2 1
  2. B. 1 2 3 5 4
  3. C. 5 4 3 2 1
  4. D. 3 2 1 4 5

Correct answer: D. 3 2 1 4 5

The first 3 go through a stack and come back reversed at the rear: 4 5 3 2 1. Then the 2 untouched items are rotated to the back: 3 2 1 4 5 — the first k elements reversed.

More Pseudocode and Code Tracing questions

Exams that ask this topic