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 小时前
手写一个 Claude Code(1):从 Agent Loop 到工具、权限、Hooks 与任务规划
python·ai编程·claude·ai agent·claudecode
m0_547486666 小时前
《Python高级编程》全套PPT课件2026(北京理工大学)
python·pycharm
Elaine3366 小时前
数据结构与算法-程序
数据结构·python·算法·计算机基础·编程基础
EatFan6 小时前
AI Agent 上生产前先加三道闸门:审批、限权、可回放的工程实践
人工智能·python·算法·多智能体·ai agent·mcp·harness
xfan_me7 小时前
维修保养记录精准版 API 对接实战指南
java·大数据·python
海上小飞龙7 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
java·c++·python
Persistent的粽子!7 小时前
双指针算法:最大盛水容器
c++·算法·leetcode
XiaoMaqqqq7 小时前
目前知名的IP驱动产业新场景新工具有哪些
网络·python·网络协议·tcp/ip
玩大数据的龙威7 小时前
农经权二轮延包—固定比例尺不定图幅的公示图批量生成
python·arcgis·二轮延包公示图
虎虎(_ _)。゜zzZ9 小时前
关于字典中的解包问题
python