Skip to content

Commit 7715ee6

Browse files
authored
Create 341. Flatten Nested List Iterator
1 parent 1af133f commit 7715ee6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

341. Flatten Nested List Iterator

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* // This is the interface that allows for creating nested lists.
3+
* // You should not implement it, or speculate about its implementation
4+
* public interface NestedInteger {
5+
*
6+
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
7+
* public boolean isInteger();
8+
*
9+
* // @return the single integer that this NestedInteger holds, if it holds a single integer
10+
* // Return null if this NestedInteger holds a nested list
11+
* public Integer getInteger();
12+
*
13+
* // @return the nested list that this NestedInteger holds, if it holds a nested list
14+
* // Return empty list if this NestedInteger holds a single integer
15+
* public List<NestedInteger> getList();
16+
* }
17+
*/
18+
public class NestedIterator implements Iterator<Integer> {
19+
20+
List<Integer> flattenList = null;
21+
int current=0;
22+
public NestedIterator(List<NestedInteger> nestedList) {
23+
flattenList= new ArrayList<>();
24+
for(NestedInteger integer:nestedList){
25+
helper(integer);
26+
}
27+
}
28+
29+
@Override
30+
public Integer next() {
31+
return flattenList.get(current++);
32+
}
33+
34+
@Override
35+
public boolean hasNext() {
36+
return current<flattenList.size();
37+
}
38+
39+
private void helper(NestedInteger value){
40+
if(value.isInteger()){
41+
flattenList.add(value.getInteger());
42+
}
43+
else{
44+
for(NestedInteger integer:value.getList()){
45+
helper(integer);
46+
}
47+
}
48+
}
49+
}
50+
51+
/**
52+
* Your NestedIterator object will be instantiated and called as such:
53+
* NestedIterator i = new NestedIterator(nestedList);
54+
* while (i.hasNext()) v[f()] = i.next();
55+
*/

0 commit comments

Comments
 (0)