leetcode-master
leetcode-master copied to clipboard
勘误【栈与队列 2.用栈实现队列】
class MyQueue:
...
def push(self, x: int) -> None:
"""
有新元素进来,就往in里面push
"""
self.stack_in.append(x)
如果我们使用pop()
之后立马使用push()
,那么存放的相对顺序就有误了,所以在函数push
中,我们应该将stack_out
中的数据先恢复到stack_int
中,即:
class MyQueue:
...
def push(self, x: int) -> None:
while self.stack_out: # 将out栈中的元素恢复到in栈中
self.stack_in.append(self.stack_out.pop())
self.stack_in.append(x) # 添加新元素