LeetCode "Implement Stack using Queues"

Two-queue solution

class Stack {
    queue<int> q;
    queue<int> q0;
    int _top;
public:
    // Push element x onto stack.
    void push(int x) {
        q.push(x);
        _top = x;
    }

    // Removes the element on top of the stack.
    void pop() {
        auto len0 = q.size();
        while(--len0)
        {
            q0.push(q.front());
            q.pop();
        }
        q.pop();
        while(!q0.empty())
        {
            q.push(_top = q0.front());
            q0.pop();
        }
    }

    // Get the top element.
    int top() {
        return _top;
    }

    // Return whether the stack is empty.
    bool empty() {
        return q.empty();
    }
};
原文地址:https://www.cnblogs.com/tonix/p/4579692.html