原题:
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].
分析
题目要求,给定一个嵌套列表,实现按照顺序访问他的迭代器
该嵌套列表的结构式,每个元素要么是整数要么是列表,然后他们的元素也是整数或者列表。
从其中可以看出,这个结构具有递归特性。所以我们应该意识到使用递归来解决该问题。
首先我们定义一个全局的vector NestVector来存放我们遍历的结果,然后定义一个全局的游标,index来标记访问到那个元素。
然后在构造函数中,通过递归方式实现对嵌套列表的访问,并将结果存入NestVector中。
对于hasNext()函数,只需要判断游标是否到达NestVector末尾即可
对于next()函数,我们只需要范围NestVector中,当前index位置处的值即可。然后对index加一即可。
代码
class NestedIterator {
public:
vector<int> NestVector;
int index;
NestedIterator(vector<NestedInteger> &nestedList) {
VisitNestedList(nestedList);
index = 0;
}
//递归遍历
void VisitNestedList(vector<NestedInteger> &nestedList){
for(int i = 0; i < nestedList.size(); i++){
if(nestedList[i].isInteger()){
NestVector.push_back(nestedList[i].getInteger());
}else{
VisitNestedList(nestedList[i].getList());
}
}
}
int next() {
return NestVector[index++];
}
bool hasNext() {
if(index < NestVector.size()){
return true;
}else{
return false;
}
}
};