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
相关推荐
___波子 Pro Max.5 分钟前
Python字典操作与应用详解
python
sg_knight8 分钟前
抽象工厂模式(Abstract Factory)
java·python·设计模式·抽象工厂模式·开发
2401_891450461 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
helloworldandy1 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
2301_790300961 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
VCR__2 小时前
python第三次作业
开发语言·python
韩立学长2 小时前
【开题答辩实录分享】以《助农信息发布系统设计与实现》为例进行选题答辩实录分享
python·web
2401_838472512 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
u0109272712 小时前
使用Python进行网络设备自动配置
jvm·数据库·python
工程师老罗2 小时前
优化器、反向传播、损失函数之间是什么关系,Pytorch中如何使用和设置?
人工智能·pytorch·python