问题描述

给定一个嵌套列表,实现一个迭代器,使其能够迭代这个列表中的所有整数。列表中的每个元素可以是整数,也可以是列表。该迭代器需要支持两个操作:next()hasNext()

示例

给定列表 = [1,[4,[6]]],
通过调用 next() 和 hasNext() 方法,迭代器依次返回:1, 4, 6。

解法一

解题思路:

我们需要实现一个迭代器,该迭代器能够遍历嵌套列表中的所有元素。为了实现这一点,我们可以使用栈来存储尚未遍历的列表,然后逐层遍历这些列表。

/** @lc app=leetcode.cn id=341 lang=javascript** [341] 扁平化嵌套列表迭代器*/// @lc code=start
class NestedIterator {constructor(nestedList) {this.stack = [];for (let i = nestedList.length - 1; i >= 0; i--) {this.stack.push(nestedList[i]);}}hasNext() {while (this.stack.length > 0) {const current = this.stack.pop();if (Array.isArray(current)) {if (current.length > 0) {this.stack.push(...current.reverse());}} else {return true;}}return false;}next() {if (!this.hasNext()) return null;const last = this.stack.pop();while (Array.isArray(last) && last.length > 0) {last.pop();this.stack.push(...last.reverse());}return last;}
}/*** Your NestedIterator will be called like this:* var i = new NestedIterator(nestedList), a = i.next();*/
// @lc code=end