Create 341. Flatten Nested List Iterator.md

This commit is contained in:
ShusenTang 2019-12-11 11:07:25 +08:00 committed by GitHub
parent 710ee25faf
commit cc5ab15011
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,46 @@
# [341. Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)
# 思路
这道题让我们将嵌套链表压平。
思路很简单因为链表的元素可能还是链表所以是个递归或者用栈转成非递归我们先创建一个记录压平后所有元素的全局数组nums
然后定义helper递归函数传入一个`NestedInteger`记为`nest`:
* 若`nest.isInteger() == True`,即`nest`是个数,将`nest.getInteger()`push进nums即可
* 否则,即`nest`是个列表,那么对`nest.getList()`的每个元素递归调用helper。
NestedIterator构造函数里面我们对nestedList每个元素调用一下`helper`以建立nums建立好nums后`hasNext()`和`next()`就好写了。
# C++
``` C++
class NestedIterator {
private:
int cur_index, size;
vector<int>nums;
void helper(NestedInteger &nest){
if(nest.isInteger())
nums.push_back(nest.getInteger());
else{
auto &list = nest.getList();
for(auto &a: list)
helper(a);
}
}
public:
NestedIterator(vector<NestedInteger> &nestedList) {
cur_index = 0;
for(auto & a: nestedList)
helper(a);
size = nums.size();
}
int next() {
return nums[cur_index++];
}
bool hasNext() {
return cur_index < size;
}
};
```