代码随想录第十天 栈和队列

第一题 很经典的栈模拟队列 https://leetcode.cn/problems/implement-queue-using-stacks/submissions/693619507/

这道题倒是没啥算法性质,主要还是模拟(话说模拟也不简单啊,挺考验思维能力的),一个栈的话只能先进后出所以怎么都无法实现先进先出的效果,所以肯定是两个栈,一个模拟入队,一个模拟出队,具体实现时是一个栈作为压入栈,在压入数据时只往这个栈中压入,记为In_stack;另一个栈只作为弹出栈,在弹出数据时只从这个栈弹出,记为out_stack。因为数据压入栈的时候,顺序是先进后出的。那么只要把In_stack的数据再压入out_stack中,顺序就变回来了,这听上去简单但是有两个要注意:

  1. 一次性全部压入 :从 in_stackout_stack转移时,必须一次性转移所有元素。

  2. 非空不压入 :只要 out_stack 不为空,就绝对不能进行转移。

违反1的情况举例:1~5依次压入in_stackin_stack的栈顶到栈底为5~1,从in_stack压入out_stack 时,只将5和4压入了out_stackout_stack 还剩下1、2、3没有压入。此时如果用户想进行弹出操作,那么4将最先弹出,与预想的队列顺序就不一致。

违反2的情况举例:1~5依次压入in_stackin_stack将所有的数据压入out_stack ,此时从out_stack 的栈顶到栈底就变成了1~5。此时又有6~10依次压入in_stackout_stack 不为空,in_stack不能向其中压入数据。如果违反2压入了out_stack ,从out_stack 的栈顶到栈底就变成了6~10、1~5。那么此时如果用户想进行弹出操作,6将最先弹出,与预想的队列顺序就不一致.

python 复制代码
class MyQueue:

    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def push(self, x: int) -> None:
        self.in_stack.append(x)

    def pop(self) -> int:
        self._help()
        return self.out_stack.pop()

    def peek(self) -> int:
        self._help()
        return self.out_stack[-1]

    def empty(self) -> bool:
        return not self.in_stack and not self.out_stack

    def _help(self):
        if not self.out_stack:
            with self.in_stack:
                self.out_stack.append(self.in_stack.pop())

def _help(self):

规则2:只有out_stack为空时才转移

if not self.out_stack:

规则1:一次性转移in_stack中的所有元素

while self.in_stack: # 这个while循环保证了"一次性全部"

self.out_stack.append(self.in_stack.pop())

相关推荐
花酒锄作田12 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪15 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽16 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战16 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama