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
相关推荐
爱学习的阿磊2 分钟前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
m0_736919106 分钟前
Python面向对象编程(OOP)终极指南
jvm·数据库·python
one____dream9 分钟前
【网安】Reverse-非常规题目
linux·python·安全·网络安全·ctf
冷雨夜中漫步19 分钟前
python反转列表reverse()和[::-1]哪个效率更高
开发语言·python
rainbow688922 分钟前
Python面向对象编程与异常处理实战
开发语言·python
weixin1997010801625 分钟前
锦程物流item_get - 获取详情接口对接全攻略:从入门到精通
数据库·python
2501_907136821 小时前
基于Python+QT6的移动硬盘弹出工具
python·软件需求
VT.馒头1 小时前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
2501_907136821 小时前
python 界面元素控件库工具,可以看到python的可视控件和使用方法
python·软件需求
2301_765703141 小时前
开发一个简单的Python计算器
jvm·数据库·python