mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 341. Flatten Nested List Iterator.md
This commit is contained in:
parent
710ee25faf
commit
cc5ab15011
46
solutions/341. Flatten Nested List Iterator.md
Normal file
46
solutions/341. Flatten Nested List Iterator.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user