|
| 1 | +/** |
| 2 | + * Flatten Nested List Iterator |
| 3 | + * |
| 4 | + * Given a nested list of integers, implement an iterator to flatten it. |
| 5 | + * |
| 6 | + * Each element is either an integer, or a list -- whose elements may also be integers or other lists. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * Given the list [[1,1],2,[1,1]], |
| 10 | + * |
| 11 | + * By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * Given the list [1,[4,[6]]], |
| 15 | + * |
| 16 | + * By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * // This is the interface that allows for creating nested lists. |
| 21 | + * // You should not implement it, or speculate about its implementation |
| 22 | + * function NestedInteger() { |
| 23 | + * |
| 24 | + * Return true if this NestedInteger holds a single integer, rather than a nested list. |
| 25 | + * @return {boolean} |
| 26 | + * this.isInteger = function() { |
| 27 | + * ... |
| 28 | + * }; |
| 29 | + * |
| 30 | + * Return the single integer that this NestedInteger holds, if it holds a single integer |
| 31 | + * Return null if this NestedInteger holds a nested list |
| 32 | + * @return {integer} |
| 33 | + * this.getInteger = function() { |
| 34 | + * ... |
| 35 | + * }; |
| 36 | + * |
| 37 | + * Return the nested list that this NestedInteger holds, if it holds a nested list |
| 38 | + * Return null if this NestedInteger holds a single integer |
| 39 | + * @return {NestedInteger[]} |
| 40 | + * this.getList = function() { |
| 41 | + * ... |
| 42 | + * }; |
| 43 | + * }; |
| 44 | + */ |
| 45 | + |
| 46 | +/** |
| 47 | + * @constructor |
| 48 | + * @param {NestedInteger[]} nestedList |
| 49 | + */ |
| 50 | +class NestedIterator { |
| 51 | + constructor(nestedList) { |
| 52 | + this.stack = nestedList.reverse(); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @this NestedIterator |
| 57 | + * @returns {boolean} |
| 58 | + */ |
| 59 | + hasNext() { |
| 60 | + while (this.stack.length > 0) { |
| 61 | + if (!isNaN(this.stack[this.stack.length - 1])) { |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + const listItem = this.stack.pop(); |
| 66 | + |
| 67 | + listItem.forEach(element => { |
| 68 | + this.stack.push(element); |
| 69 | + }); |
| 70 | + } |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @this NestedIterator |
| 76 | + * @returns {integer} |
| 77 | + */ |
| 78 | + next() { |
| 79 | + return this.stack.pop(); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | + * Your NestedIterator will be called like this: |
| 85 | + * var i = new NestedIterator(nestedList), a = []; |
| 86 | + * while (i.hasNext()) a.push(i.next()); |
| 87 | + */ |
| 88 | + |
| 89 | +export { NestedIterator }; |
0 commit comments