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]
.
一种特殊的数据结构 NestedInteger 由 int 和 list 组成(里面的数据有可能是一个int,也有可能是一个list),而这个list里面又可能由 int 和 list 组成
现在要设计一个迭代器类 NestedIterator,通过调用类的接口函数next() 和 hasNext(),可以依次输出里面所有的 int 。
NestedInteger目前提供三个接口,
bool isInteger() const; //返回当前NestedInteger是否是一个int int getInteger() const; //如果当前NestedInteger是int,返回int const vector<NestedInteger> &getList() const; ////如果当前NestedInteger是list,以const vector<NestedInteger>的形式返回list
可以调用这三个接口依次获得每个int,用一个vector<int>来保存。
具体实现方式,对于每个NestedInteger
1、用isInteger()判断是否为int
2.1、如果是一个int,用getInteger()获取值并存入,接着处理下一个NestedInteger
2.2、如果是一个list,就调用vector<NestedInteger> &getList()对应的vector<NestedInteger>,并对里面的NestedInteger重复1和2
1 class NestedIterator { 2 private: 3 vector<int> v; 4 int pos = 0; 5 void Data_Construct(const NestedInteger &ni) { 6 if (ni.isInteger()) 7 v.push_back(ni.getInteger()); 8 else { 9 const vector<NestedInteger> vn = ni.getList(); 10 for (int i = 0; i < vn.size(); ++i) 11 Data_Construct(vn[i]); 12 } 13 } 14 public: 15 NestedIterator(vector<NestedInteger> &nestedList) { 16 for (int i = 0; i < nestedList.size(); ++i) 17 Data_Construct(nestedList[i]); 18 } 19 20 int next() { 21 return v[pos++]; 22 } 23 24 bool hasNext() { 25 return pos < v.size(); 26 } 27 };