pranay_teja
11/16/2018 - 12:01 PM

StackUsingTwoQueues


// https://www.youtube.com/watch?v=xBugrptVRUQ
// https://www.youtube.com/watch?v=Wn45fJKBTTc

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

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */