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
相关推荐
203号居民8 分钟前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
2301_8000742128 分钟前
map,list简单方法
windows·python·list
玖玥拾30 分钟前
LeetCode 202 快乐数
算法·leetcode
DeepVisionary1 小时前
30B 参数打平 1 万亿参数:Meta 开源 Muse Glimmer,跑分 35 对 36
python·自动化
吴声子夜歌2 小时前
Guava——基本工具(二)
windows·python·guava
Tim_102 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
用户8356290780513 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
猎嘤一号3 小时前
【2026 最新】Windows 11 右键菜单还原为 Windows 10 经典样式:一条命令、原理、回退与新版说明
windows·python
用户8356290780513 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python