# 341. Flatten Nested List Iterator

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/flatten-nested-list-iterator/description/

> 内容描述

```
Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:

Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,1,2,1,1].
Example 2:

Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,4,6].
```

## 解题方案

> 思路 1

这个思路就是先把nestedList里面所有的Integer全部拿出来放到一个stack里面，next()就是简单的拿出下一个，hasNext()就是简单的看看还有没有下一个，但是这样会有一个不好的地方就是如果在现实中，我们的nestedList很大很大，然后我们可能只调用一次next()，那岂不是很亏吗。后面的解法会解决这个问题


```python
class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        def dfs(nestedList):
            for item in nestedList:
                if item.isInteger():
                    self.stack.append(item.getInteger())
                else:
                    dfs(item.getList())
        self.stack = []
        dfs(nestedList)
        

    def next(self):
        """
        :rtype: int
        """
        if self.hasNext():
            return self.stack.pop(0)


    def hasNext(self):
        """
        :rtype: bool
        """
        return self.stack != []
```

> 思路 2

参考大神[StefanPochmann](https://leetcode.com/problems/flatten-nested-list-iterator/discuss/80146/Real-iterator-in-Python-Java-C++)
其实还是有一个stack，但是每次只把当前非空的nestedList加进来，然后递归嵌套调用的思想，取出最后一个。


```python
class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack = [[nestedList, 0]]
    

    def next(self):
        """
        :rtype: int
        """
        cur_nestedList, i = self.stack[-1]
        self.stack[-1][1] += 1
        return cur_nestedList[i]


    def hasNext(self):
        """
        :rtype: bool
        """
        s = self.stack
        while s:
            cur_nestedList, i = s[-1]
            if i == len(cur_nestedList):
                s.pop()
            else:
                x = cur_nestedList[i]
                if x.isInteger(): # x is a Integer
                    return True
                else:             # x is still a nestedList
                    s[-1][1] += 1
                    s.append([x.getList(), 0])
        return False
```
