232. 用栈实现队列
题目来源:力扣(leetcode)https://leetcode-cn.com/problems/implement-queue-using-stacks/
题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你只能使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
进阶:
- 你能否实现每个操作均摊时间复杂度为
O(1)
的队列?换句话说,执行n
个操作的总时间复杂度为O(n)
,即使其中一个操作可能花费较长时间。
示例:
输入:
["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
- 最多调用
100
次push
、pop
、peek
和empty
- 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop
或者peek
操作)
解题思路
思路:栈
题目要求我们是使用两个栈实现队列。这里先说下栈和队列:
- 栈:一种后进先出(LIFO)的数据结构。
- 队列:一种先进先出(FIFO)的数据结构。
为了实现队列,满足先进先出(FIFO)的特性。我们引入两个栈,其中一个栈作为输入栈,用于 p u s h {\rm push} push 操作,而另外一个栈作为输出栈,反转元素,用于 p o p {\rm pop} pop 和 p e e k {\rm peek} peek 操作。下面说下具体的思路:
- 声明两个栈,分别为 in_stack 和 out_stack;
- 对于
p
u
s
h
{\rm push}
push 操作:
- 将元素压入 in_stack 中;
- 对于
p
o
p
{\rm pop}
pop 操作,分情况:
- 当 out_stack 为空时,先将 in_stack 中的元素移动到 out_stack 中,然后将 out_stack 栈顶元素弹出并返回;
- 当 out_stack 不为空时,将 out_stack 栈顶元素弹出并返回;
- 对于
p
e
e
k
{\rm peek}
peek 操作,分情况(与
p
o
p
{\rm pop}
pop 操作不同于不需要弹出栈顶元素):
- 当 out_stack 为空时,先将 in_stack 中的元素移动到 out_stack 中,然后将 out_stack 栈顶元素返回;
- 当 out_stack 不为空时,将 out_stack 栈顶元素返回;
- 对于
e
m
p
t
y
{\rm empty}
empty 操作:
- 判断两个栈是否都为空,都为空返回 True,否则返回 False。
借示例,用图示的形式展示,如下图:
具体代码实现如下。
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.in_stack = []
self.out_stack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
# 添加元素
self.in_stack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
# out_stack 不为空,弹出并返回栈顶元素
# 否则先将 in_stack 中的元素移动到 out_stack 中再弹出并返回栈顶元素
if not self.out_stack:
self.in_to_out()
return self.out_stack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
# 与 pop 方法类似,但是不弹出栈顶元素
if not self.out_stack:
self.in_to_out()
return self.out_stack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
# 两个栈均为空,才表示队列为空
return not self.in_stack and not self.out_stack
def in_to_out(self):
"""
Moves the element of the in_stack to the out_stack
"""
# 将 in_stack 中的元素移动到 out_stack 中
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
复杂度分析
-
时间复杂度:其中 p u s h {\rm push} push 和 e m p t y {\rm empty} empty 操作时间复杂度为 O ( 1 ) O(1) O(1),而 p o p {\rm pop} pop 和 p e e k {\rm peek} peek 操作的均摊时间复杂度为 O ( 1 ) O(1) O(1)。
p o p {\rm pop} pop 和 p e e k {\rm peek} peek 操作,最坏的情况下时间复杂度为 O ( n ) O(n) O(n), n n n 表示队列的大小。即是 out_stack为空时,需要移动元素,进行出栈入栈的操作,时间复杂度为 O ( n ) O(n) O(n),但后续的操作,时间复杂度为 O ( 1 ) O(1) O(1),摊还后均摊时间复杂度为 O ( 1 ) O(1) O(1)。
-
空间复杂度: O ( n ) O(n) O(n)。
欢迎关注
公众号 【书所集录】
如有错误,烦请指出,欢迎指点交流。若觉得写得还不错,麻烦点个赞👍,谢谢。