# LeetCode: Flatten Nested List Iterator Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * // This is the interface that allows for creating nested lists.3 * // You should not implement it, or speculate about its implementation4 * 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 integer13 *     Return null if this NestedInteger holds a nested list14 *     @return {integer}15 *     this.getInteger = function() {16 *         ...17 *     };18 *19 *     Return the nested list that this NestedInteger holds, if it holds a nested list20 *     Return null if this NestedInteger holds a single integer21 *     @return {NestedInteger[]}22 *     this.getList = function() {23 *         ...24 *     };25 * };26 */27/**28 * @constructor29 * @param {NestedInteger[]} nestedList30 */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 NestedIterator46 * @returns {boolean}47 */48NestedIterator.prototype.hasNext = function () {49  return this.array.length50}51
52/**53 * @this NestedIterator54 * @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