Stack using Queue, making Pop costly (via class and object)

 #include <bits/stdc++.h>
using namespace std;
//making pop operation costly
class stk
{
private:
    queue<intq1q2;

public:
    void psh()
    {
        int x;
        cout << "Enter the value: ";
        cin >> x;
        q1.push(x);
    }
    void popp()
    {
        int x;
        if (q1.empty())
        {
            cout << "Stack already empty! \n";
            return;
        }
        while (!q1.empty() && q1.back() != q1.front())
        {
            x = q1.front();
            q2.push(x);
            q1.pop();
        }
        q1.pop();
        while (!q2.empty())
        {
            x = q2.front();
            q1.push(x);
            q2.pop();
        }
    }
    void print()
    {
        int x;
        q2 = q1;
        if (q1.empty())
        {
            cout << "Stack is empty! \n";
            return;
        }
        cout << "Bottom-> ";
        while (!q2.empty())
        {
            cout << q2.front() << " ";
            q2.pop();
        }
        cout << "<-Top\n";
    }
};
int main()
{
    int choice = 1chx;
    stk s1;
    while (choice)
    {
        cout << "ENTER 1. to push in stack ";
        cout << "\nENTER 2. to pop from stack";
        cout << "\nENTER 3. to print stack.\nEnter choice: ";
        cin >> ch;
        if (ch == 1)
            s1.psh();
        else if (ch == 2)
            s1.popp();
        else if (ch == 3)
            s1.print();
        cout << "Do you want to continue (0/1) : ";
        cin >> choice;
    }
}

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