Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Data Structures & Algorithms

Stack & Queue

Applications
Implement Queue Using Stacks
• enqueue(5);
• enqueue(2);
• enqueue(3);
Implement Queue Using Stacks
• enqueue(5);
• enqueue(2);
• enqueue(3);

In the above stack, we can observe that the topmost element is 3. If we


perform the delete operation in the above stack, then the element 3 would
be deleted from the stack. On the other hand, the deletion in Queue is
performed from the front end and the front element is 5. In order to
implement the Queue using Stack, we need to consider two stacks.
Implement Queue Using Stacks
• Suppose we have two stacks named as Stack1 and Stack2 shown as below:
Implement Queue Using Stacks
As we can observe that above stacks are empty. Now, we will perform push
operations on the Stack1. First, we will push 5, then 2 and finally we will push
element 3 shown as below:
Implement Queue Using Stacks
As we can observe that above stacks are empty. Now, we will perform push
operations on the Stack1. First, we will push 5, then 2 and finally we will push
element 3 shown as below:
Implement Queue Using Stacks
Now we will pop the elements from the Stack1 one by one and push them
into the Stack2 as shown as below:
Implement Queue Using Stacks
Now we will pop the elements from the Stack1 one by one and push them
into the Stack2 as shown as below:
Implement Queue Using Stacks
Once the elements are inserted into the Stack2, the topmost element is 5 so it
would be popped out from the Stack 2 shown as below:
Implement Queue Using Stacks
Once the topmost element is popped out from the Stack2, all the elements
are moved back from Stack2 to Stack 1 shown as below:
Implement Queue Using Stacks
There are two approaches to implement Queue using Stack:

1. Making a dequeue operation costly

2. Making a enqueue operation costly


Thank You

You might also like