Implement Stack using Queues

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        if(q1.empty()&&q2.empty())
            q1.push(x);
        else if(!q1.empty())
            q1.push(x);
        else
            q2.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        if(!q1.empty())
        {
            while(q1.size()!=1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            q1.pop();
        }
        else if(!q2.empty())
        {
            while(q2.size()!=1)
            {
                q1.push(q2.front());
                q2.pop();
            }
            q2.pop();
        }
    }

    // Get the top element.
    int top() {
        int t;
        if(!q1.empty())
        {
            while(q1.size()!=1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            t=q1.front();
            q2.push(t);
            q1.pop();
        }
        else if(!q2.empty())
        {
            while(q2.size()!=1)
            {
                q1.push(q2.front());
                q2.pop();
            }
            t=q2.front();
            q1.push(t);
            q2.pop();
        }
        return t;
    }

    // Return whether the stack is empty.
    bool empty() {
        if(q1.empty()&&q2.empty())
            return true;
        else
            return false;
    }
private:
    queue<int> q1;
    queue<int> q2;
};

 

posted on 2016-05-09 10:00  summerkiki  阅读(154)  评论(0编辑  收藏  举报