跳转至

225.用队列实现栈*

题目描述*

使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

代码*

队列实现栈,在插入的时候把之前的结点都放到后面。{}

class MyStack {
private:
    queue<int> innerQueue;
public:
    /** Initialize your data structure here. */
    MyStack() {
        ;
    }

    /** Push element x onto stack. */
    void push(int x) {
        innerQueue.push(x);
        int len = innerQueue.size();
        while(len > 1) {
            innerQueue.push(innerQueue.front());
            innerQueue.pop();
            len--;
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        if(innerQueue.empty()) {
            return -1;
        }
        int tmp = innerQueue.front();
        innerQueue.pop();
        return tmp;
    }

    /** Get the top element. */
    int top() {
        if(innerQueue.empty()) {
            return -1;
        }
        return innerQueue.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return innerQueue.empty();
    }
};

最后更新: July 23, 2022