|
| 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 | +function flat(arr, res) { |
| 32 | + for(let i = 0; i < arr.length; i++) { |
| 33 | + if(arr[i].isInteger()) { |
| 34 | + res.push(arr[i].getInteger()) |
| 35 | + } else { |
| 36 | + flat(arr[i].getList() ,res) |
| 37 | + } |
| 38 | + |
| 39 | + } |
| 40 | +} |
| 41 | +const NestedIterator = function(nestedList) { |
| 42 | + this.arr = [] |
| 43 | + this.idx = -1 |
| 44 | + flat(nestedList, this.arr) |
| 45 | +}; |
| 46 | + |
| 47 | + |
| 48 | +/** |
| 49 | + * @this NestedIterator |
| 50 | + * @returns {boolean} |
| 51 | + */ |
| 52 | +NestedIterator.prototype.hasNext = function() { |
| 53 | + return this.idx + 1 < this.arr.length |
| 54 | +}; |
| 55 | + |
| 56 | +/** |
| 57 | + * @this NestedIterator |
| 58 | + * @returns {integer} |
| 59 | + */ |
| 60 | +NestedIterator.prototype.next = function() { |
| 61 | + this.idx += 1 |
| 62 | + return this.arr[this.idx] |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Your NestedIterator will be called like this: |
| 67 | + * var i = new NestedIterator(nestedList), a = []; |
| 68 | + * while (i.hasNext()) a.push(i.next()); |
| 69 | +*/ |
0 commit comments