Answer to Question #247978 in C for xyz

Question #247978

Develop an algorithm to implement Stack using Queue data structure.


1
Expert's answer
2021-10-07T03:10:12-0400


#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;
}

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