Implement Stack using Queues

This is implemented using two queue: Insertion:- O(1) Deletion:- O(n)

class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int> i;
    queue<int> d;
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        i.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int k;
        while(i.size()!=1){
            k = i.front();
            d.push(k);
            i.pop();
        }
        
        k = i.front();
        i.pop();
        
        while(!d.empty()){
            int s = d.front();
            i.push(s);
            d.pop();   
        }
        
        return k;
    }
    
    /** Get the top element. */
    int top() {
        int k;
        k = i.back();
        return k;  
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        if(i.empty()){
            return true;
        }
        return false;
    }
};

Last updated