Implement a Stack Using Queue
We have a Queue data structure and we need to implement a Stack Data structure from it. We know that Stack have Last in First out scheme of entering and exiting whereas we have First in First Out scheme in a Queue, keeping this in mind we can either make changes to the enqueue() function to accommodate a stack or make changes to dequeue() function for the same.
Let's see how we can change enqueue() to implement a stack
for pushing in a stack-> Newly entered element is always at the front of 'q1', so that pop operation just dequeues from 'q1'. 'q2' is used to put every new element at front of 'q1'.
1.push(s,x)
- enqueue x to q2
- one by one dequeue everything from q1 and enqueue to q2
- swap name of q1 and q2
Dequeue item from q1 and return it
Code-->
//implement a stack using 2 queues,
class Stack{
queue<int> q1,q2;
int cur_size;
public:
Stack()
{
cur_size=0;
}
void push(int x)
{
cur_size++;
//push x first in empty q2
q2.push(x);
//push remaining elements in q1 to q2
while(!q1.empty())
q2.push(q1.front());
q1.pop();
queue<int> q= q1;
q1=q2;
q2=q;
}
void pop()
{
if(q1.empty())
return;
q1.pop();
cur_size--;
}
int top()
{
if(q1.empty())
return -1;
return q1.front();
}
int size()
{
return cur_size;
}
};