# LeetCode: Flatten Nested List Iterator Solution

1/**
2 * // This is the interface that allows for creating nested lists.
3 * // You should not implement it, or speculate about its implementation
4 * function NestedInteger() {
5 *
6 * Return true if this NestedInteger holds a single integer, rather than a nested list.
7 * @return {boolean}
8 * this.isInteger = function() {
9 * ...
10 * };
11 *
12 * Return the single integer that this NestedInteger holds, if it holds a single integer
13 * Return null if this NestedInteger holds a nested list
14 * @return {integer}
15 * this.getInteger = function() {
16 * ...
17 * };
18 *
19 * Return the nested list that this NestedInteger holds, if it holds a nested list
20 * Return null if this NestedInteger holds a single integer
21 * @return {NestedInteger[]}
22 * this.getList = function() {
23 * ...
24 * };
25 * };
26 */
27/**
28 * @constructor
29 * @param {NestedInteger[]} nestedList
30 */
31
32const flatten = nestedList => {
33 return nestedList.flatMap(nestedInteger =>
34 nestedInteger.isInteger()
35 ? nestedInteger.getInteger()
36 : flatten(nestedInteger.getList())
37 )
38}
39
40var NestedIterator = function (nestedList) {
41 this.array = flatten(nestedList)
42}
43
44/**
45 * @this NestedIterator
46 * @returns {boolean}
47 */
48NestedIterator.prototype.hasNext = function () {
49 return this.array.length
50}
51
52/**
53 * @this NestedIterator
54 * @returns {integer}
55 */
56NestedIterator.prototype.next = function () {
57 return this.array.shift()
58}
59
60/**
61 * Your NestedIterator will be called like this:
62 * var i = new NestedIterator(nestedList), a = [];
63 * while (i.hasNext()) a.push(i.next());
64 */

leetcode

stack

recursion

## Next Post

CSSBattle 1.2: Carrom

Apr 13, 2021

Search Posts