-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path341. Flatten Nested List Iterator.py
More file actions
72 lines (61 loc) · 2.42 KB
/
Copy path341. Flatten Nested List Iterator.py
File metadata and controls
72 lines (61 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.stack = [[nestedList,0]]
def next(self) -> int:
self.make_stack_top_an_integer()
cur_lst = self.stack[-1][0]
cur_index = self.stack[-1][1]
self.stack[-1][1] += 1
return cur_lst[cur_index].getInteger()
def hasNext(self) -> bool:
self.make_stack_top_an_integer()
return len(self.stack) > 0
def make_stack_top_an_integer(self):
while self.stack:
cur_lst = self.stack[-1][0]
cur_index = self.stack[-1][1]
if len(cur_lst) == cur_index:
self.stack.pop()
continue
if cur_lst[cur_index].isInteger():
break
new_lst = cur_lst[cur_index].getList()
self.stack[-1][1] += 1
self.stack.append([new_lst,0])
# class NestedIterator: #Soln 1 - DFS iterative
# def __init__(self, nestedList: [NestedInteger]):
# self.stack = list(reversed(nestedList))
# # print(self.stack)
# def next(self) -> int:
# self.make_stack_top_an_integer()
# return self.stack.pop().getInteger()
# def hasNext(self) -> bool:
# self.make_stack_top_an_integer()
# return len(self.stack) > 0
# def make_stack_top_an_integer(self):
# while self.stack and not self.stack[-1].isInteger():
# self.stack.extend(reversed(self.stack.pop().getList()))
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())