You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# 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
+
26
+
27
+
28
+
fromcollectionsimportdeque
29
+
# Approach 1: Brite force ut not good for the interview. This approach, modifies the input list
30
+
classNestedIterator(object):
31
+
32
+
def__init__(self, nestedList):
33
+
"""
34
+
Initialize your data structure here.
35
+
:type nestedList: List[NestedInteger]
36
+
"""
37
+
self.q=deque()
38
+
self.flatten(nestedList)
39
+
40
+
defflatten(self, nestedList):
41
+
forlinnestedList:
42
+
ifl.isInteger():
43
+
self.q.append(l.getInteger())
44
+
else:
45
+
self.flatten(l.getList())
46
+
47
+
defnext(self):
48
+
"""
49
+
:rtype: int
50
+
"""
51
+
returnself.q.popleft()
52
+
53
+
defhasNext(self):
54
+
"""
55
+
:rtype: bool
56
+
"""
57
+
returnlen(self.q) >0
58
+
59
+
60
+
61
+
62
+
# Approach 2: This approach, doesn't modify the input list but depends on hasNext to be called, which is also not good and not the perfect implementation for the interview
0 commit comments