题目:
题解:
struct NestedIterator {
int *vals;
int size;
int cur;
};
void dfs(struct NestedIterator *iter, struct NestedInteger **nestedList, int nestedListSize) {
for (int i = 0; i < nestedListSize; i++) {
if (NestedIntegerIsInteger(nestedList[i])) {
(iter->vals)[(iter->size)++] = NestedIntegerGetInteger(nestedList[i]);
} else {
dfs(iter, NestedIntegerGetList(nestedList[i]), NestedIntegerGetListSize(nestedList[i]));
}
}
}
struct NestedIterator *nestedIterCreate(struct NestedInteger **nestedList, int nestedListSize) {
struct NestedIterator *ret = malloc(sizeof(struct NestedIterator));
ret->vals = malloc(sizeof(int) * 20001);
ret->size = 0;
ret->cur = 0;
dfs(ret, nestedList, nestedListSize);
return ret;
}
bool nestedIterHasNext(struct NestedIterator *iter) {
return iter->cur != iter->size;
}
int nestedIterNext(struct NestedIterator *iter) {
return (iter->vals)[(iter->cur)++];
}
void nestedIterFree(struct NestedIterator *iter) {
free(iter->vals);
free(iter);
}