Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
shenmuxin opened this issue Feb 28, 2024 · 0 comments
Open

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

shenmuxin opened this issue Feb 28, 2024 · 0 comments

Comments

@shenmuxin
Copy link

【栈与队列 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)     # 添加新元素
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant