import java.util.*;
// Given Interface (Leetcode style)
interface NestedInteger {
boolean isInteger();
Integer getInteger();
List<NestedInteger> getList();
}
// Implementation for testing
class NI implements NestedInteger {
private Integer value;
private List<NestedInteger> list;
public NI(Integer val) {
this.value = val;
this.list = null;
}
public NI(List<NestedInteger> list) {
this.list = list;
this.value = null;
}
@Override
public boolean isInteger() {
return value != null;
}
@Override
public Integer getInteger() {
return value;
}
@Override
public List<NestedInteger> getList() {
return list;
}
}
// Iterator class
class NestedIterator implements Iterator<Integer> {
private Queue<Integer> q = new LinkedList<>();
public NestedIterator(List<NestedInteger> nestedList) {
flatten(nestedList);
}
private void flatten(List<NestedInteger> nestedList) {
for (NestedInteger ni : nestedList) {
if (ni.isInteger()) {
q.add(ni.getInteger());
} else {
flatten(ni.getList());
}
}
}
@Override
public Integer next() {
return q.poll();
}
@Override
public boolean hasNext() {
return !q.isEmpty();
}
}
public class Main {
public static void main(String[] args) {
// Input: [[1,1], 2, [1,1]]
List<NestedInteger> input = new ArrayList<>();
input.add(new NI(Arrays.asList(new NI(1), new NI(1))));
input.add(new NI(2));
input.add(new NI(Arrays.asList(new NI(1), new NI(1))));
NestedIterator i = new NestedIterator(input);
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
}
}