Flatten Nested List Iterator LeetCode solution in JavaScript

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
var NestedIterator = function (nestedList) {
32
this.nestedList = [];
33
this.ptr = 0;
34
const dfs = (elem) => {
35
if (!elem.isInteger()) {
36
let list = elem.getList();
37
for (let i = 0; i < list.length; i++) {
38
dfs(list[i]);
39
}
40
} else {
41
this.nestedList.push(elem.getInteger());
42
}
43
};
44
for (let i = 0; i < nestedList.length; i++) {
45
dfs(nestedList[i]);
46
}
47
};
48

49
/**
50
* @this NestedIterator
51
* @returns {boolean}
52
*/
53
NestedIterator.prototype.hasNext = function () {
54
if (this.ptr < this.nestedList.length) return true;
55
else return false;
56
};
57

58
/**
59
* @this NestedIterator
60
* @returns {integer}
61
*/
62
NestedIterator.prototype.next = function () {
63
return this.nestedList[this.ptr++];
64
};
65

66
/**
67
* Your NestedIterator will be called like this:
68
* var i = new NestedIterator(nestedList), a = [];
69
* while (i.hasNext()) a.push(i.next());
70
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0