Implement Stack using Queues

https://leetcode.com/problems/implement-stack-using-queues/

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

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

    // Get the top element.
    int top() {
        if(!q1.empty())
            return q1.back();
        else
            return q2.back();
    }

    // Return whether the stack is empty.
    bool empty() {
        if(q1.empty()&&q2.empty())
            return true;
        else
            return false;
    }
};

  

原文地址:https://www.cnblogs.com/aguai1992/p/5029418.html