How many stacks are needed to implement a queue? Consider the situation where…
2025
How many stacks are needed to implement a queue? Consider the situation where no other data structure like arrays or linked lists is available to you.
Answer: B. 2 — To implement a queue using only stacks, you need exactly 2 stacks. One stack handles enqueue operations by pushing elements directly onto it. The second stack…
- A.
1
- B.
2
- C.
3
- D.
4
Attempted by 628 students.
Show answer & explanation
Correct answer: B
To implement a queue using only stacks, you need exactly 2 stacks. One stack handles enqueue operations by pushing elements directly onto it. The second stack manages dequeue operations, transferring all elements from the first stack to reverse their order before popping.
When the second stack is empty during dequeue, transfer all remaining elements from the first stack to reverse their order. This ensures FIFO behavior while maintaining only two stacks throughout all operations.