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