用栈实现队列
难度:简单
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
双栈
思路:
将一个栈当作输入栈,用于压入 push \texttt{push} push 传入的数据;另一个栈当作输出栈,用于 pop \texttt{pop} pop 和 peek \texttt{peek} peek 操作。
每次 pop \texttt{pop} pop 或 peek \texttt{peek} peek 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。
复杂度分析:
- 时间复杂度: push \texttt{push} push 和 empty \texttt{empty} empty 为 O ( 1 ) O(1) O(1), pop \texttt{pop} pop 和 peek \texttt{peek} peek 为均摊 O ( 1 ) O(1) O(1)。对于每个元素,至多入栈和出栈各两次,故均摊复杂度为 O ( 1 ) O(1) O(1)。
- 空间复杂度: O ( n ) O(n) O(n)。其中 n n n 是操作总数。对于有 n n n 次 push \texttt{push} push 操作的情况,队列中会有 n n n 个元素,故空间复杂度为 O ( n ) O(n) O(n)。
class MyQueue:
def __init__(self):
self.stack1 = list()
self.stack2 = list()
def push(self, x: int) -> None:
self.stack1.append(x)
def pop(self) -> int:
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
def peek(self) -> int:
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def empty(self) -> bool:
if not self.stack1 and not self.stack2:
return True
return False
# 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()
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-queue-using-stacks