题目表述:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 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
- 最多调用
100
次push
、pop
、peek
和empty
- 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop
或者peek
操作)
力扣链接:
思路分析:
本题的要求是写一个MyQueue类,具体是用栈结构实现队列,要求实现push,pop,peek,empty等常用的队列功能。
其中push是将元素x加入到队列的末尾,pop是从队列的开头移除并返回元素, peek是返回队列开头的元素,empty是判断队列是否为空。
看到这些要求,首先我们需要明白,栈和队列的区别,栈最大的特性就是先进后出,而队列最大的特性就是先进先出。要使用栈来实现队列的功能,我们需要用到两个栈来抵消先进后出的特性,达到先进先出的效果,具体实现可以看下面代码分析中的pop方法中else板块的内容。
另一个需要注意的点就是,用这两个栈来实现队列的pop操作时,一定要先一次性将第一个栈的所有元素全部pop完,然后append到第二个栈中后,再进行第二个栈的pop操作,否则顺序会乱。
代码分析:
class MyQueue:
def __init__(self):
"""
用两个栈结构(python里面用列表来实现)来模拟队列的先进先出特性
in主要负责push, out主要负责pop
"""
self.stack_in = [] # 定义第一个栈作为输入栈
self.stack_out =[] # 定义第二个栈作为输出栈
def push(self, x: int) -> None:
"""
有新元素进来, 就往stack_in这个栈里面push,用append来实现
"""
self.stack_in.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element
"""
if self.empty(): # 首先判断要pop元素的栈是否为空
return None
if self.stack_out: # 如果输出栈不为空,对输出栈进行pop操作
return self.stack_out.pop()
else: # 如果输出栈为空,则先从输入栈中将所有元素转移到输出栈,然后再pop输出栈
for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
"""
Get the front element.
"""
ans = self.pop() # 从stack_out栈中pop元素,然后将该元素添加到stack_out栈中
self.stack_out.append(ans)
return ans
def empty(self) -> bool:
"""
只要in或者out有元素,说明队列不为空
"""
return not (self.stack_in or self.stack_out)
# 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()