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
相关推荐
人机(未转人工)6 分钟前
python 批量测试ip是否能ping( 多线程 )
python
cndes10 分钟前
安装Miniconda+Jupyter notebook
ide·python·jupyter
Patrick在香港19 分钟前
Python 拉取城巴开放数据:406 条路线,香港岛巴士网络的数字画像
网络·python·数据分析·php·数据可视化·香港·开放数据
for_ever_love__29 分钟前
python基础语法学习: 正则表达式
python·学习·正则表达式
aiqianji31 分钟前
功能全面的教AI短篇小说写作的软件都有哪些?
人工智能·python
轮到我狗叫了1 小时前
Slurm如何使用
人工智能·python·深度学习·机器学习
Ali885201 小时前
Python列表增删改查速查表和详细演示
python
新时代牛马2 小时前
softirq 与tasklet:从irq_exit 到__do_softirq 的下半部路径
python
tqs_123452 小时前
值传递与引用传递
java·开发语言·python
YsyaaabB2 小时前
Deep Agents 实战课程
python·langchain