Answer to Question #248041 in C++ for Myname

Question #248041
Write a program to implementation a Queue using stacks.
(You may follow the link for hint: https://www.geeksforgeeks.org/queue-using-stacks/)
1
Expert's answer
2021-10-07T14:00:28-0400
#include <iostream>
#include<stack>
using namespace std;
 
struct Queue {
    stack<int> s1, s2;
 
    void enQueue(int x)
    {
        
        while (!s1.empty()) {
            s2.push(s1.top());
            s1.pop();
        }
 
       
        s1.push(x);
 
        
        while (!s2.empty()) {
            s1.push(s2.top());
            s2.pop();
        }
    }
 
    
    int deQueue()
    {
        
        if (s1.empty()) {
            cout << "Q is Empty";
            exit(0);
        }
 
        
        int x = s1.top();
        s1.pop();
        return x;
    }
};
 


int main()
{
    Queue q;
    q.enQueue(1);
    q.enQueue(2);
    q.enQueue(3);
 
    cout << q.deQueue() << '\n';
    cout << q.deQueue() << '\n';
    cout << q.deQueue() << '\n';
 
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS