Home » Data Structure & Algorithms » Implement stack using queue

Implement stack using queue


Question :

WAP to implement a stack(LIFO) using queues(FIFO).

If you are not aware of what is stack ?Please see the stack tutorial.

Algorithm :

Iterative Solution :

Declare two queues q1 and q2 .

push(Object obj) 
            Step 1 : Enqueue obj to q2
            Step 2 : One by one dequeue each element from q1 and enqueue to q2.
            Step 3 : Swap the names of q1 and q2

            Step 1 : Dequeue an item from q1 and return it.

Program :


OutPut  :


Leave a comment

Your email address will not be published. Required fields are marked *

eighteen + nineteen =