leetcode-master icon indicating copy to clipboard operation
leetcode-master copied to clipboard

勘误【栈与队列 2.用栈实现队列】

Open shenmuxin opened this issue 11 months ago • 0 comments

【栈与队列 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)     # 添加新元素

shenmuxin avatar Feb 28 '24 07:02 shenmuxin