@@ -102,32 +102,37 @@ def __isComplete(self) -> bool:
102
102
return self .__position >= len (self .__nestedList )
103
103
104
104
105
+
106
+ # Most optimal and preferd approach
105
107
# https://tinyurl.com/rotxca8
108
+ # Debug the code to get a clear idea
106
109
class NestedIterator (object ):
107
110
108
111
def __init__ (self , nestedList ):
109
- self .nestedListStack = [[nestedList , 0 ]] # <list, next element index/position>
112
+ self .nestedListStack = [[nestedList , 0 ]] # <list, current element index/position on the nested list >
110
113
111
114
# Here, next method does't have any dependency over hasNext
112
115
def next (self ):
113
- # print("------")
114
- # print("1 self.nestedListStack: ", self.nestedListStack)
115
- self .hasNext ()
116
- # print("2 self.nestedListStack: ", self.nestedListStack)
117
- nestedList , position = self .nestedListStack [- 1 ]
118
- self .nestedListStack [- 1 ][1 ] += 1
119
- return nestedList [position ].getInteger ()
116
+ currentNestedListStack = self .nestedListStack
117
+ nestedList , currentPositionIdx = currentNestedListStack [- 1 ]
118
+ currentNestedListStack [- 1 ][
119
+ 1 ] += 1 # updating currentPositionIdx by 1, since we are sending the current integer here, on next line
120
+ return nestedList [currentPositionIdx ].getInteger ()
120
121
121
122
def hasNext (self ):
122
123
currentNestedListStack = self .nestedListStack
123
124
while currentNestedListStack :
124
- nestedList , position = currentNestedListStack [- 1 ]
125
- if position == len (nestedList ):
126
- currentNestedListStack .pop () # this nestedList is already processed, remove from stack
125
+ nestedList , currentPositionIdx = currentNestedListStack [- 1 ]
126
+ if currentPositionIdx == len (nestedList ): # we are done with this nested list, let's pop it out.
127
+ currentNestedListStack .pop ()
127
128
else :
128
- currentItem = nestedList [position ]
129
+ currentItem = nestedList [currentPositionIdx ]
129
130
if currentItem .isInteger ():
130
131
return True
131
132
currentNestedListStack [- 1 ][1 ] += 1 # incremets current nestedListStack index
132
133
currentNestedListStack .append ([currentItem .getList (), 0 ])
133
- return False
134
+ return False
135
+
136
+ # Your NestedIterator object will be instantiated and called as such:
137
+ # i, v = NestedIterator(nestedList), []
138
+ # while i.hasNext(): v.append(i.next())
0 commit comments