题目链接

题目描述

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):
实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

    示例

    示例1:

    输入: [“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false]

    解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1

myQueue.pop(); // return 1, queue is [2]

myQueue.empty(); // return false

提示

  • 1 <= x <= 9
  • 最多调用 100pushpoppeekempty
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

    思路

    双栈

    设置两个栈 stackInstackOut

  • void push(int x) 直接将元素加入 stackIn 即可。

  • int pop()stackOut 为空,则将 stackIn 栈顶弹出并压入 stackOut 中,直到 stackIn 为空,然后弹出 stackOut 栈顶;若stackOut 不为空,则直接弹出 stackOut 栈顶。
  • int peek() 返回队列开头的元素,返回 stackOut 栈顶,若 stackOut 为空,则将 stackIn 栈顶弹出并压入 stackOut 中,直到 stackIn 为空
  • boolean empty() ,当两个栈都为空的时候返回真。

    题解

    ```cpp class MyQueue { private: stack stackIn; stack stackOut;

    void move() {

    1. while (!stackIn.empty()) {
    2. stackOut.push(stackIn.top());
    3. stackIn.pop();
    4. }

    }

    public: /* Initialize your data structure here. / MyQueue() { }

    /* Push element x to the back of queue. / void push(int x) {

      stackIn.push(x);
    

    }

    /* Removes the element from in front of queue and returns that element. / int pop() {

      if (stackOut.empty()) {
          this->move();
      }
      int ret = stackOut.top();
      stackOut.pop();
      return ret;
    

    }

    /* Get the front element. / int peek() {

      if (stackOut.empty()) {
          move();
      }
      return stackOut.top();
    

    }

    /* Returns whether the queue is empty. / bool empty() {

      return stackIn.empty() && stackOut.empty();
    

    } };

/**

  • Your MyQueue object will be instantiated and called as such:
  • MyQueue* obj = new MyQueue();
  • obj->push(x);
  • int param_2 = obj->pop();
  • int param_3 = obj->peek();
  • bool param_4 = obj->empty(); */ ```

    复杂度分析

  • 时间复杂度:0232-用栈实现队列 - 图1
  • 空间复杂度:0232-用栈实现队列 - 图2