|
| 1 | +/** |
| 2 | + * 341. Flatten Nested List Iterator |
| 3 | + * https://leetcode.com/problems/flatten-nested-list-iterator/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a nested list of integers nestedList. Each element is either an integer or a list |
| 7 | + * whose elements may also be integers or other lists. Implement an iterator to flatten it. |
| 8 | + * |
| 9 | + * Implement the NestedIterator class: |
| 10 | + * - NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list |
| 11 | + * nestedList. |
| 12 | + * - int next() Returns the next integer in the nested list. |
| 13 | + * - boolean hasNext() Returns true if there are still some integers in the nested list and false |
| 14 | + * otherwise. |
| 15 | + * |
| 16 | + * Your code will be tested with the following pseudocode: |
| 17 | + * initialize iterator with nestedList |
| 18 | + * res = [] |
| 19 | + * while iterator.hasNext() |
| 20 | + * append iterator.next() to the end of res |
| 21 | + * return res |
| 22 | + * |
| 23 | + * If res matches the expected flattened list, then your code will be judged as correct. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @constructor |
| 28 | + * @param {NestedInteger[]} nestedList |
| 29 | + */ |
| 30 | +var NestedIterator = function(nestedList) { |
| 31 | + this.stack = []; |
| 32 | + this.flatten(nestedList); |
| 33 | +}; |
| 34 | + |
| 35 | +/** |
| 36 | + * @this NestedIterator |
| 37 | + * @param {NestedInteger[]} nestedList |
| 38 | + * @returns {void} |
| 39 | + */ |
| 40 | +NestedIterator.prototype.flatten = function(list) { |
| 41 | + for (let i = list.length - 1; i >= 0; i--) { |
| 42 | + this.stack.push(list[i]); |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | +/** |
| 47 | + * @this NestedIterator |
| 48 | + * @returns {boolean} |
| 49 | + */ |
| 50 | +NestedIterator.prototype.hasNext = function() { |
| 51 | + while (this.stack.length > 0 && !this.stack[this.stack.length - 1].isInteger()) { |
| 52 | + const nested = this.stack.pop().getList(); |
| 53 | + this.flatten(nested); |
| 54 | + } |
| 55 | + return this.stack.length > 0; |
| 56 | +}; |
| 57 | + |
| 58 | +/** |
| 59 | + * @this NestedIterator |
| 60 | + * @returns {integer} |
| 61 | + */ |
| 62 | +NestedIterator.prototype.next = function() { |
| 63 | + return this.stack.pop().getInteger(); |
| 64 | +}; |
0 commit comments