How to implement Stack using Queue?

Ayush Said

+0 -0

The approach to implementing a stack using two queues is as follows:
i) Initialize two queues: queue1 and queue2.
ii) For each push operation, add the new element to queue1.
iii) For each pop operation, transfer all elements from queue1 to queue2 except the last one, which is removed and returned.
iv) Swap queue1 and queue2 so that queue1 is always the empty queue, ready for the next push operation.

Submit Your Response