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
相关推荐
Codefengfeng1 小时前
Python Base环境中加包的方法
开发语言·python
清水白石0081 小时前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
如若1232 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
甲枫叶2 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
清水白石0083 小时前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python
紫陌涵光3 小时前
669. 修剪二叉搜索树
算法·leetcode
勇往直前plus4 小时前
深入理解 Python 内存模型:模块、类、对象的存储与运行机制
开发语言·python
yunhuibin4 小时前
NIN网络学习
人工智能·python·深度学习·神经网络·学习
派大星-?4 小时前
自动化测试五模块一框架(下)
开发语言·python
两万五千个小时5 小时前
构建mini Claude Code:02 - 把 Bash 拆成专用工具(read_file, write_file 等)
人工智能·python