扁平化嵌套列表迭代器
问题:
给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的每一项或者为一个 整数 ,或者是另一个 列表 。其中列表的元素也可能是 ==整数 或是其他 列表 。
思路:
- 采用深度优先策略(dfs)递归嵌套整型列表,将所有整数放入数组。
- 初始化迭代器 it 。
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
vector<int> vec;
vector<int>::iterator it;
void dfs(const vector<NestedInteger>& nestedList) {
for(auto const& next : nestedList) {
if(next.isInteger()) {
vec.push_back(next.getInteger());
}
else dfs(next.getList());
}
}
public:
NestedIterator(const vector<NestedInteger> &nestedList) {
dfs(nestedList);
it = vec.begin();
}
int next() {
return *it++;
}
bool hasNext() {
return it != vec.end();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/