Implement Stack using only one Queue.
#include <bits/stdc++.h>
using namespace std;
class stk
{
private:
queue<int> q1;
public:
void psh(int x)
{
q1.push(x);
//After pushing each value (let x),
//pop all values in-front of this value(x),
// one by one and push them a end of queue.
for (int i = 0; i < q1.size() - 1; i++)
{
q1.push(q1.front());
q1.pop();
}
}
void pp()
{
if (q1.empty())
{
cout << "Stack is empty\n";
}
else
{
cout << "Popped: " << q1.front() << endl;
q1.pop();
}
}
void pek()
{
if (q1.empty())
{
cout << "Stack is empty\n";
}
else
{
cout << "Stack Top: " << q1.front();
}
}
};
int main()
{
stk a;
int ch = 1, choice, x;
while (ch != 0)
{
cout << "Enter 1 to push\n";
cout << "Enter 2 to pop\n";
cout << "Enter 3 to peek\n";
cin >> choice;
if (choice == 1)
{
cout << "Enter value : ";
cin >> x;
a.psh(x);
}
else if (choice == 2)
a.pp();
else if (choice == 3)
a.pek();
cout << "Do you want to continue (0 to exit) : ";
cin >> ch;
}
}
Comments
Post a Comment