[LeetCode][Python]Flatten Nested List Iterator

 Flatten Nested List Iterator

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:
Given the list [[1,1],2,[1,1]],

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

Example 2:
Given the list [1,[4,[6]]],

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

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


展平嵌套的list。

从调用的方式来看,总会调用到最后,所以在构造函数中递归展开所有的数放到一位数组中。

另一种方式是把nested list压到栈中,需要的时候再从栈中拿。

注意需要调用注释中的isInteger(),getInteger()和getList()三个方法。

 1 # """
 2 # This is the interface that allows for creating nested lists.
 3 # You should not implement it, or speculate about its implementation
 4 # """
 5 #class NestedInteger(object):
 6 #    def isInteger(self):
 7 #        """
 8 #        @return True if this NestedInteger holds a single integer, rather than a nested list.
 9 #        :rtype bool
10 #        """
11 #
12 #    def getInteger(self):
13 #        """
14 #        @return the single integer that this NestedInteger holds, if it holds a single integer
15 #        Return None if this NestedInteger holds a nested list
16 #        :rtype int
17 #        """
18 #
19 #    def getList(self):
20 #        """
21 #        @return the nested list that this NestedInteger holds, if it holds a nested list
22 #        Return None if this NestedInteger holds a single integer
23 #        :rtype List[NestedInteger]
24 #        """
25 class NestedIterator(object):
26     
27     def __init__(self, nestedList):
28         """
29         Initialize your data structure here.
30         :type nestedList: List[NestedInteger]
31         """
32         self.__list = []
33         self.__index = 0
34         self.__getList(nestedList)
35         
36     def __getList(self, nestedList):
37         for item in nestedList:
38             if item.isInteger():
39                 self.__list.append(item.getInteger())
40             else:
41                 self.__getList(item.getList())
42 
43     def next(self):
44         """
45         :rtype: int
46         """
47         res = self.__list[self.__index]
48         self.__index += 1
49         return res
50 
51     def hasNext(self):
52         """
53         :rtype: bool
54         """
55         if(self.__index < len(self.__list)):
56             return True
57         return False
原文地址:https://www.cnblogs.com/Liok3187/p/5489848.html