# Stack using Queues in C++
We have to implement functionalities of a stack data structure using queue data structure.
Queue is a
FIFO
– first in first out data structure.Stack is a
LIFO
– last in first out data structure.Functionalities of a stack data structure are :
push()
- insert a element at the top.pop()
- removing element from the top stack.top()
– to get the element at the top.size()
– to get the total number of elements in the stack.empty()
– to check if the stack is empty or not.
Functionalities of a queue data structure are :
enqueue()
- insert a element at the rear.dequeue()
- removing element from the front.front()
– to get the element at the front.size()
– to get the total number of elements in the stack.empty()
– to check if the stack is empty or not.
To make a stack using queue, considering
front
in a queue as thetop
of the stack, we need to add functionalities of a stack to to it. Considering thefront
as thetop
of the stack we can see that we can perfrom thepop()
function using thedequeue()
function in queue as it will remove the element from thefront/top
.The
top()
method will be replaced byfront()
, andsize()
andempty()
remain common for both.So now we only have to make a method
push()
to add an element at the front of the queue to achieve all the functionalities of a stack.Steps to implement a
push()
method:- Using two queues
primary_queue
&secondary_queue
. - enqueue the element to be inserted in secondary_queue.
- While
primary_queue
not empty, enqueue (insert) the element at front ofprimary_queue
to thesecondary_queue
and dequeue (remove) that element from theprimary_queue
. - Swap
primary_queue
withsecondary_queue
.
- Using two queues
# Source Code - C++
#include <iostream>
#include <queue>
using namespace std;
class Stack {
queue<int> primary_queue, secondary_queue;
public:
void push(int element){
// enqueue in secondary_queue
secondary_queue.push(element);
// add elements of primary_queue to secondary_queue
while(!primary_queue.empty()){
secondary_queue.push(primary_queue.front());
primary_queue.pop();
}
// swapping the queues
queue<int> temp_queue = primary_queue;
primary_queue = secondary_queue;
secondary_queue = temp_queue;
}
void pop(){
if(primary_queue.empty()){
return;
} else {
primary_queue.pop();
}
}
int top(){
if(primary_queue.empty()){
return -1;
} else {
return primary_queue.front();
}
}
void displayStack()
{
queue<int> temp_queue = primary_queue;
while(!temp_queue.empty()){
cout<<temp_queue.front()<<" ";
temp_queue.pop();
}
cout<<"\n";
}
};
int main(){
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.displayStack();
cout<<"Top: "<<s.top()<<"\n";
s.pop();
s.displayStack();
return 0;
}
Learn More
- Stack using Queues in C++