Implementation of Queue using Two Stacks in C++
Implementation of Queue using Two Stacks
Queue and stack are fundamentally two different linear data structures, but given with one or more of any one data structures, we can just convert it into other and apply it in real. This article is about the Implementation of Queue using Two Stacks with the help of a Queue named class and two stacks inside it as member variables.
Implementation of Queue using Two Stacks | PrepInsta
Stack vs Queue?
Stack is a data structure where you get Last in First out implementation, and queue is with first in first out implementation.
So, it seems impossible to turn a stack into a queue. Though by basic using of two stacks we can implement a queue very easily : Queue By 2 stacks.
The Algorithm to create a Queue using two Stacks
Here we are going to discuss the algorithm of how we can make a queue using just two stacks. To visualise it more clearly here a class with the name “Queue” has been created, where there will be just two stacks as member variables and the member functions will be working as the functions to access or manipulate the queue. We will use the stack in C++ STl as the stack.
- So, we take two stacks, s1 and s2.
s1 will be working as the main queue and s2 will help us in reversing the order of s1.
- The basic difference between a stack and a queue is the popping process, that is called Dequeue for the queue. If you think the top of the stack is the back of the queue, the pushing process is the same. But the popping will be in the reverse order. So we will use a stack (s2) temporarily to reverse the values.
- So, the pushing will be pushing to s1.
- To pop elements from the back, we will pop out elements from s1 and push it in s2.
- Then pop only one element.
- Then again push them into s1. The order of them won’t change for the queue.
- Same algorithm will be used to check the front value of the queue.
The code to implement this:
Pushing the element : 5
Pushing the element : 2
Pushing the element : 11
The Queue now is : 1 5 2 11
The front value right now is : 1
Popping the element : 1
Popping the element : 5
Pushing the element : 12
Pushing the element : 8
The front value right now is : 2
The Queue now is : 2 11 12 8