Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]],By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
Example 2:Given the list [1,[4,[6]]],By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
这道题要把嵌套的数组读成不嵌套的数组
利用栈,先把给的list里的所有的NestedInteger从后往前压入栈,NestedInteger可能就是一个数,也可能是一个list(注意这里的这个list可能是空的),从栈顶开始取,取出来的是数就读出来,是list就把list展开压进去,list是空的就跳过。
var NestedIterator = function(nestedList) {
this.stack = [];
for (var i = nestedList.length-1;i >= 0 ;i--) {
this.stack.push(nestedList[i]);
}
};
NestedIterator.prototype.hasNext = function() {
while (this.stack.length!==0) {
var temp = this.stack[this.stack.length-1];
if (temp.isInteger())
return true;
else {
temp = temp.getList();
this.stack.pop();
if (temp.length!==0) {
for (var i = temp.length-1;i >= 0 ;i--) {
this.stack.push(temp[i]);
}
}
}
}
return false;
};
NestedIterator.prototype.next = function() {
var tamp = this.stack.pop();
return tamp.getInteger();
};