LeetCode/solutions/341. Flatten Nested List Iterator.md
2019-12-11 11:07:25 +08:00

47 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```