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 null if this NestedInteger holds a single integer
15
+ * public List<NestedInteger> getList();
16
+ * }
17
+ */
18
+ public class NestedIterator implements Iterator <Integer > {
19
+ List <Integer > list ;
20
+ int i =0 ;
21
+ public NestedIterator (List <NestedInteger > nestedList ) {
22
+ list = getList (nestedList , new ArrayList <>());
23
+ }
24
+
25
+ public List <Integer > getList (List <NestedInteger > list , List <Integer > output ) {
26
+ for (NestedInteger n : list ) {
27
+ if (n .isInteger ()) {
28
+ output .add (n .getInteger ());
29
+ } else {
30
+ getList (n .getList (), output );
31
+ }
32
+ }
33
+ return output ;
34
+ }
35
+
36
+ @ Override
37
+ public Integer next () {
38
+ return list .get (i ++);
39
+ }
40
+
41
+ @ Override
42
+ public boolean hasNext () {
43
+ if (i == list .size ())
44
+ return false ;
45
+ return true ;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Your NestedIterator object will be instantiated and called as such:
51
+ * NestedIterator i = new NestedIterator(nestedList);
52
+ * while (i.hasNext()) v[f()] = i.next();
53
+ */
0 commit comments