题目大意: 解嵌套,将一个数据可嵌套的类的整型值序列化。
思路:遍历一棵多叉树,如果是叶子节点就把结果加在list中,如果不是,就继续遍历这个子树。
AC code:
class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
flat(nestedList);
listIter = mList.begin();
}
int next() {
int res = *listIter;
++listIter;
return res;
}
bool hasNext() {
return listIter != mList.end();
}
void flat(vector<NestedInteger>& nL){
for (auto &it : nL) {
if (it.isInteger())
mList.push_back(it.getInteger());
else
flat(it.getList());
}
}
private:
list<int>::iterator listIter;
list<int>mList;
};
A后感:思路不复杂,但是花了很长时间才ac,居然卡在了list迭代器初始化上。
在选择暂存结果的container的时候,发生了一些奇怪的问题:
#include <iostream>
#include <vector>
#include <list>
#include <deque>
using namespace std;
int main() {
list<int> ss; // list or vector or deque
auto it = ss.begin();
cout<<boolalpha<<(it == ss.end())<<endl;
ss.push_back(555);
ss.push_back(666);
it++;
cout<<*it<<endl;
return 0;
}
以上的代码,使用不同的容器,编译得到的结果是不一样的,应该是它们的内部实现不同导致的。