Implementation of stack using Queue
This code is used to implement a stack using a queue.
Source Code :
#include <bits/stdc++.h>
using namespace std;
class Stack
{
int N;
queue<int> q1;
queue<int> q2;
public:
Stack()
{
N = 0;
}
void push(int val)
{
q2.push(val);
N++;
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
queue<int> temp = q1;
q1 = q2;
q2 = temp;
}
void give_()
{
cout << “This is the front portion : “ << q1.front() << endl;
cout << “This is the back portion : “ << q1.back() << endl;
}
void pop()
{
q1.pop();
N — ;
}
int top()
{
cout << “The top Element is : “;
return q1.front();
}
int size()
{
cout << “The size of stack is : “;
return N;
}
};
int main()
{
Stack a;
a.push(1);
a.push(2);
a.push(3);
a.push(4);
a.pop();
cout << a.top() << endl;
cout << a.size() << endl;
a.push(5);
cout << a.top() << endl;
cout << a.size() << endl;
return 0;
}
Output :-