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:
Input: [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,1,2,1,1]
Example 2:
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,4,6]
题意:给出一个嵌套的节点列表,其中每个节点要么为一个整数,要么为一个列表。要求为每次输入的列表实现一个迭代器,能够按序输出其中的元素。
思路:从第一个列表开始遍历其每个元素,若为整型,存放到队列中,否则递归求解该子列表。
class NestedIterator {
public:
queue<int>que;
void solve(vector<NestedInteger> & tmp){
for(int i=0;i<tmp.size();i++)
{
if(tmp[i].isInteger())
que.push(tmp[i].getInteger());
else{
solve(tmp[i].getList());
}
}
}
NestedIterator(vector<NestedInteger> &nestedList) {
for(int i=0;i<nestedList.size();i++){
if(nestedList[i].isInteger()){
que.push(nestedList[i].getInteger());
}else{
solve(nestedList[i].getList());
}
}
}
int next() {
int tmp=que.front();
que.pop();
return tmp;
}
bool hasNext() {
return que.size()==0?0:1;
}
};