Skip to content

Commit 7043957

Browse files
committed
add Flatten Nested List Iterator
1 parent f2f9a6c commit 7043957

File tree

3 files changed

+189
-0
lines changed

3 files changed

+189
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@
228228
* 227. [Basic Calculator II](Stack/227_BasicCalculatorII.py)
229229
* 232. [Implement Queue using Stacks](Stack/232_ImplementQueueUsingStacks.py)
230230
* 316. [Remove Duplicate Letters](Stack/316_RemoveDuplicateLetters.py)
231+
* 341. [Flatten Nested List Iterator](Stack/341_FlattenNestedListIterator.py)
231232

232233
# [Two Pointers](TwoPointers/)
233234

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* @Author: [email protected]
3+
* @Last Modified time: 2016-07-09 14:38:26
4+
*/
5+
6+
/**
7+
* // This is the interface that allows for creating nested lists.
8+
* // You should not implement it, or speculate about its implementation
9+
* class NestedInteger {
10+
* public:
11+
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
12+
* bool isInteger() const;
13+
*
14+
* // Return the single integer that this NestedInteger holds, if it holds a single integer
15+
* // The result is undefined if this NestedInteger holds a nested list
16+
* int getInteger() const;
17+
*
18+
* // Return the nested list that this NestedInteger holds, if it holds a nested list
19+
* // The result is undefined if this NestedInteger holds a single integer
20+
* const vector<NestedInteger> &getList() const;
21+
* };
22+
*/
23+
class NestedIterator {
24+
public:
25+
/*
26+
According to:
27+
https://discuss.leetcode.com/topic/42042/simple-java-solution-using-a-stack-with-explanation
28+
29+
In the constructor, we push all the nestedList into the stack from back to front,
30+
so when we pop the stack, it returns the very first element.
31+
Second, in the hasNext() function, we peek the first element in stack currently,
32+
and if it is an Integer, we will return true and pop the element.
33+
34+
If it is a list, we will further flatten it.
35+
This is iterative version of flatting the nested list.
36+
Again, we need to iterate from the back to front of the list.
37+
*/
38+
stack<NestedInteger> keep;
39+
NestedIterator(vector<NestedInteger> &nestedList) {
40+
for(auto it=nestedList.rbegin(); it!=nestedList.rend(); it++){
41+
keep.push(*it);
42+
}
43+
}
44+
45+
int next() {
46+
int val = keep.top().getInteger();
47+
keep.pop();
48+
return val;
49+
}
50+
51+
bool hasNext() {
52+
while(!keep.empty()){
53+
NestedInteger cur = keep.top();
54+
if(cur.isInteger()){
55+
return true;
56+
}
57+
keep.pop();
58+
vector<NestedInteger> new_list = cur.getList();
59+
for(auto it=new_list.rbegin(); it!=new_list.rend(); it++){
60+
keep.push(*it);
61+
}
62+
}
63+
return false;
64+
}
65+
};
66+
67+
/**
68+
* Your NestedIterator object will be instantiated and called as such:
69+
* NestedIterator i(nestedList);
70+
* while (i.hasNext()) cout << i.next();
71+
*/
72+
73+
/*
74+
[]
75+
[1,[2,[3]]]
76+
[[1,2],3,[4,5]]
77+
[[[1,2,3], [4,5], 7], [8,9], 10]
78+
*/
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
#! /usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# @Last Modified time: 2016-07-09 14:22:29
5+
6+
# """
7+
# This is the interface that allows for creating nested lists.
8+
# You should not implement it, or speculate about its implementation
9+
# """
10+
#class NestedInteger(object):
11+
# def isInteger(self):
12+
# """
13+
# @return True if this NestedInteger holds a single integer, rather than a nested list.
14+
# :rtype bool
15+
# """
16+
#
17+
# def getInteger(self):
18+
# """
19+
# @return the single integer that this NestedInteger holds, if it holds a single integer
20+
# Return None if this NestedInteger holds a nested list
21+
# :rtype int
22+
# """
23+
#
24+
# def getList(self):
25+
# """
26+
# @return the nested list that this NestedInteger holds, if it holds a nested list
27+
# Return None if this NestedInteger holds a single integer
28+
# :rtype List[NestedInteger]
29+
# """
30+
31+
32+
class NestedIterator(object):
33+
"""
34+
According to:
35+
https://discuss.leetcode.com/topic/42042/simple-java-solution-using-a-stack-with-explanation
36+
37+
In the constructor, we push all the nestedList into the stack from back to front,
38+
so when we pop the stack, it returns the very first element.
39+
Second, in the hasNext() function, we peek the first element in stack currently,
40+
and if it is an Integer, we will return true and pop the element.
41+
42+
If it is a list, we will further flatten it.
43+
This is iterative version of flatting the nested list.
44+
Again, we need to iterate from the back to front of the list.
45+
"""
46+
def __init__(self, nestedList):
47+
"""Initialize your data structure here.
48+
49+
:type nestedList: List[NestedInteger]
50+
"""
51+
self.stack = []
52+
for item in nestedList[::-1]:
53+
self.stack.append(item)
54+
55+
def next(self):
56+
val = self.stack[-1].getInteger()
57+
self.stack.pop()
58+
return val
59+
60+
def hasNext(self):
61+
while self.stack:
62+
curr = self.stack[-1]
63+
if curr.isInteger():
64+
return True
65+
self.stack.pop()
66+
if curr.getList():
67+
for i in curr.getList()[::-1]:
68+
self.stack.append(i)
69+
return False
70+
71+
72+
class NestedIterator_2(object):
73+
""" Python Generators solution
74+
75+
According to:
76+
https://discuss.leetcode.com/topic/45844/python-generators-solution
77+
"""
78+
def __init__(self, nestedList):
79+
"""Initialize your data structure here.
80+
"""
81+
def gen(nestedList):
82+
for item in nestedList:
83+
if item.isInteger():
84+
yield item.getInteger()
85+
else:
86+
for list in gen(item.getList()):
87+
yield list
88+
89+
self.gen = gen(nestedList)
90+
91+
def next(self):
92+
return self.value
93+
94+
def hasNext(self):
95+
try:
96+
self.value = next(self.gen)
97+
return True
98+
except StopIteration:
99+
return False
100+
101+
# Your NestedIterator object will be instantiated and called as such:
102+
# i, v = NestedIterator(nestedList), []
103+
# while i.hasNext(): v.append(i.next())
104+
105+
'''
106+
[]
107+
[1,[2,[3]]]
108+
[[1,2],3,[4,5]]
109+
[[[1,2,3], [4,5], 7], [8,9], 10]
110+
'''

0 commit comments

Comments
 (0)