Develop an algorithm to implement Stack using Queue data structure.
#include <iostream>
#include <queue>
using namespace std;
class Stack {
queue<int> que1, que2;
int curr_size;
public:
Stack()
{
curr_size = 0;
}
void push(int x)
{
curr_size++;
que2.push(x);
while (!que1.empty()) {
que2.push(que1.front());
que1.pop();
}
queue<int> que = que1;
que1 = que2;
que2 = que;
}
void pop()
{
if (que1.empty())
return;
que1.pop();
curr_size--;
}
int top()
{
if (que1.empty())
return -1;
return que1.front();
}
int size()
{
return curr_size;
}
};
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "current size: " << s.size()
<< endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
cout << "current size: " << s.size()
<< endl;
return 0;
}
Comments
Leave a comment