Implement Stack using only one Queue.

#include <bits/stdc++.h>
using namespace std;
class stk
{
private:
    queue<intq1;

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 = 0i < q1.size() - 1i++)
        {
            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 = 1choicex;
    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

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree