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
相关推荐
Betelgeuse7618 小时前
Django 中间件 4 大钩子 & CBV vs FBV 对比实战
python·中间件·django
92year1 天前
用Google ADK从零搭一个能调工具的AI Agent:Python实操全过程
python·ai·mcp
洛水水1 天前
【力扣100题】18.随机链表的复制
算法·leetcode·链表
woxihuan1234561 天前
SQL删除数据时存在依赖关系_设置外键级联删除ON DELETE
jvm·数据库·python
Jetev1 天前
如何确定SQL字段是否为空_使用IS NULL与IS NOT NULL
jvm·数据库·python
蛐蛐蛐1 天前
昇腾910B4上安装新版本CANN的正确流程
人工智能·python·昇腾
m0_702036531 天前
mysql如何处理不走索引的OR查询_使用UNION ALL优化重写
jvm·数据库·python
2401_846339561 天前
MySQL在云环境如何选择存储类型_SSD与高性能云盘配置建议
jvm·数据库·python
2601_957780841 天前
Claude 4.6 对阵 GPT-5.4:2026 开发者大模型 API 选型深度解析
人工智能·python·gpt·ai·claude
2601_957780841 天前
GPT-5.5 深度解析:2026年4月OpenAI旗舰模型的技术跨越与商业决策指南
大数据·人工智能·python·gpt·openai