zhangdizhangdi

225. 用队列实现栈 🟩

题目

leetcode 简单

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

注意:
你只能使用队列的标准操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:
输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]

输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

题解

方法:两个队列

  • 时间复杂度
    • 入栈(push)操作 O(n)
    • 其余(pop,top,empty)操作都是 O(1)
  • 空间复杂度:O(n)
js
class MyStack {
  constructor() {
    this.q1 = [] // 主队列
    this.q2 = [] // 辅助队列
  }

  push(x) {
    // 1. 新元素先入 q2
    this.q2.push(x)

    // 2. 将 q1 中的元素全部依次出队,并入队到 q2 后面
    while (this.q1.length > 0) {
      this.q2.push(this.q1.shift())
    }

    // 3. 交换 q1 和 q2。现在 q1 又是包含了所有元素且顺序正确的队列了
    // q2 再次变成空队列,等待下一次 push
    let temp = this.q1
    this.q1 = this.q2
    this.q2 = temp
  }

  pop() {
    // 队列头部就是栈顶
    return this.q1.shift()
  }

  top() {
    // 返回队列头部元素
    return this.q1[0]
  }

  empty() {
    return this.q1.length === 0
  }
}

const stack = new MyStack()
stack.push(1)
stack.push(2)
console.log(stack.top()) // 返回 2
console.log(stack.pop()) // 返回 2
stack.push(3)
console.log(stack.top()) // 返回 3
console.log(stack.empty()) // 返回 False
执行结果
2
2
3
false

方法:一个队列

  • 时间复杂度
    • 入栈(push)操作 O(n)
    • 其余(pop,top,empty)操作都是 O(1)
  • 空间复杂度:O(n)
js
class MyStack {
  constructor() {
    this.queue = []
  }

  push(x) {
    // 1. 记录下在 x 进来之前,队列里有几个老元素
    const n = this.queue.length

    // 2. 将新元素入队(此时它在队尾)
    this.queue.push(x)

    // 3. 将前面的 n 个老元素依次出队,并立刻重新入队到队尾
    for (let i = 0; i < n; i++) {
      // shift() 取出队头,push() 塞到队尾
      this.queue.push(this.queue.shift())
    }
  }

  pop() {
    // 经过 push 的神奇旋转,队头已经是栈顶了
    return this.queue.shift()
  }

  top() {
    return this.queue[0]
  }

  empty() {
    return this.queue.length === 0
  }
}

const stack = new MyStack()
stack.push(1)
stack.push(2)
console.log(stack.top()) // 返回 2
console.log(stack.pop()) // 返回 2
stack.push(3)
console.log(stack.top()) // 返回 3
console.log(stack.empty()) // 返回 False
执行结果
2
2
3
false