Leetcode 225. 用队列实现栈

通过判断队列是否为空来找到栈顶

class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int> que[2];
    int f;
    MyStack() {
        f = 0;
    }

    /** Push element x onto stack. */
    void push(int x) {
        que[f].push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int x;
        while (!que[f].empty()) {
            x = que[f].front();
            que[f].pop();
            if(!que[f].empty())que[1 - f].push(x);
        }
        f ^= 1;
        return x;
    }

    /** Get the top element. */
    int top() {
        int x;
        while (!que[f].empty()) {
            x = que[f].front();
            que[f].pop();
            que[1 - f].push(x);
        }
        f ^= 1;
        return x;
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que[f].empty();
    }
};

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/Bendaai/article/details/81251832