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
相关推荐
pzx_00135 分钟前
【优化器】 随机梯度下降 SGD 详解
人工智能·python·算法
大邳草民35 分钟前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
小肝一下44 分钟前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
程序员小远1 小时前
软件测试用例总结
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
2501_948114241 小时前
技术解码:Gemini交互式模拟API与高负载网关的选型逻辑
人工智能·python·ai
AC赳赳老秦1 小时前
OpenClaw text-translate技能:多语言批量翻译,解决跨境工作沟通难题
大数据·运维·数据库·人工智能·python·deepseek·openclaw
JaydenAI1 小时前
[Python编程思想与技巧-01]我所理解的Python元模型
python·元宇宙·元类·元模型
清水白石0082 小时前
《Python 架构师的自动化哲学:从基础语法到企业级作业调度系统与 Airflow 止损实战》
数据库·python·自动化
kaico20182 小时前
python操作数据库
开发语言·数据库·python
zhangzeyuaaa2 小时前
Python变量的四种作用域
开发语言·python