leetcode+ 队列模拟栈,pop使用双队列,topValue记录栈顶值

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

class MyStack {
public:
    queue<int> Q, tmp;
    int topValue;
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        Q.push(x);
        topValue = x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        while (Q.size()>1) {
            tmp.push(Q.front());
            Q.pop();
        }
        int remove_val = Q.front(); //删除元素
        Q.pop();
        while (tmp.size()>0) {
            Q.push(tmp.front());
            tmp.pop();
        }
        topValue = Q.back();
        return remove_val;
    }
    
    /** Get the top element. */
    int top() {
        return topValue;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return Q.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/u013554860/article/details/81094778
今日推荐