LeetCode 225. 用队列实现栈

364 阅读3分钟

leetcode.cn/problems/im…

programmercarl.com/0225.%E7%94…

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

实现 MyStack 类:

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

 

注意:

  • 你只能使用队列的标准操作 —— 也就是 push to backpeek/pop from frontsize 和 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

 

提示:

  • 1 <= x <= 9
  • 最多调用100 次 pushpoptop 和 empty
  • 每次调用 pop 和 top 都保证栈不为空

 

进阶: 你能否仅用一个队列来实现栈。

(这里要强调是单向队列)

队列模拟栈,其实一个队列就够了,那么我们先说一说两个队列来实现栈的思路。

队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。

所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。

但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的!

如下面动画所示,用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。

225.用队列实现栈

  • 时间复杂度: pop为O(n),top为O(n),其他为O(1)
  • 空间复杂度: O(n)

其实这道题目就是用一个队列就够了。

一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

解法一:

优化,使用一个 Queue 实现

class MyStack {
    var queue: Queue<Int> = LinkedList()

    //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
    fun push(x: Int) {
        queue.offer(x)
        var size = queue.size
        //移动除了 A 的其它数
        while (size-- > 1) queue.offer(queue.poll())
    }

    fun pop(): Int {
        return queue.poll()
    }

    fun top(): Int {
        return queue.peek()
    }

    fun empty(): Boolean {
        return queue.isEmpty()
    }
}
  • 时间复杂度: pop为O(n),top为O(n),其他为O(1)
  • 空间复杂度: O(n)

解法二:

使用双端队列。

class MyStack() {

    /** Initialize your data structure here. */
    var queue = ArrayDeque<Int>()

    /** Push element x onto stack. */
    fun push(x: Int) {
        queue.addLast(x)
    }

    /** Removes the element on top of the stack and returns that element. */
    fun pop(): Int {
        return queue.pollLast()
    }

    /** Get the top element. */
    fun top(): Int {
        return queue.peekLast()
    }

    /** Returns whether the stack is empty. */
    fun empty(): Boolean {
        return queue.isEmpty()
    }
}
  • 时间复杂度: pop为O(n),top为O(n),其他为O(1)
  • 空间复杂度: O(n)