Python | Leetcode Python题解之第341题扁平化嵌套列表迭代器

题目:

题解:

python 复制代码
class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        # 对于nestedList中的内容,我们需要从左往右遍历,
        # 但堆栈pop是从右端开始,所以我们压栈的时候需要将nestedList反转再压栈
        self.stack = nestedList[::-1]

    def next(self) -> int:
        # hasNext 函数中已经保证栈顶是integer,所以直接返回pop结果
        return self.stack.pop(-1).getInteger()

    def hasNext(self) -> bool: 
        # 对栈顶进行'剥皮',如果栈顶是List,把List反转再依次压栈,
        # 然后再看栈顶,依次循环直到栈顶为Integer。
        # 同时可以处理空的List,类似[[[]],[]]这种test case           
        while len(self.stack) > 0 and self.stack[-1].isInteger() is False:
            self.stack += self.stack.pop().getList()[::-1]
        return len(self.stack) > 0
相关推荐
曲幽4 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780519 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞12 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派14 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪16 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636716 小时前
将 PDF 文档转换为图片【Python 教程】
python
xlp666hub16 小时前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
悟空爬虫17 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派17 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风19 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python