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].
2 尝试解
2.1 分析
先把NestedListt展开,作为一个向量即可。
2.2 代码
class NestedIterator {
public:
int index = 0;
vector<int> list;
NestedIterator(vector<NestedInteger> &nestedList) {
list.clear();
Flatten(list,nestedList);
}
int next() {
index++;
return list[index-1];
}
bool hasNext() {
return index < list.size();
}
void Flatten(vector<int>& result, vector<NestedInteger>&nestedList){
for(auto obj : nestedList){
if(obj.isInteger())
result.push_back(obj.getInteger());
else
Flatten(result,obj.getList());
}
}
};
3 标准解
class NestedIterator {
public:
typedef vector<NestedInteger>::iterator iter;
NestedIterator(vector<NestedInteger> &nestedList) {
begins.push(nestedList.begin());
ends.push(nestedList.end());
}
int next() {
return begins.top()++->getInteger();
}
bool hasNext() {
while(!begins.empty()) {
iter it = begins.top();
if(it == ends.top()) {
begins.pop();
ends.pop();
if(!begins.empty()) begins.top()++;
} else if (it->isInteger()) return 1;
else {
vector<NestedInteger>& lst = it->getList();
begins.push(lst.begin());
ends.push(lst.end());
}
}
return 0;
}
private:
stack<iter> begins, ends;
};