/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
interface NestedInteger {
public boolean isInteger();
public List<NestedInteger> getList();
}
static class NestedIntegerIterator {
private final List<NestedInteger> list;
private Stack<Iterator<NestedInteger>> stack;
public NestedIntegerIterator(List<NestedInteger> list) {
this.list = list;
stack = new Stack<Iterator<NestedInteger>>();
stack.push(list.iterator());
advance();
}
public boolean hasNext() {
return stack.empty() == false;
}
advance();
return next;
}
private void advance() {
while (stack.empty() == false) {
Iterator<NestedInteger> it = stack.peek();
if (it.hasNext() == false) {
stack.pop();
} else {
NestedInteger ni = it.next();
if (ni.isInteger()) {
this.nextInteger = ni.getInteger();
break;
} else {
stack.push(ni.getList().iterator());
}
}
}
}
}
static class NestedIntegerImpl implements NestedInteger {
public NestedIntegerImpl(int val) {
this.val = val;
}
return this.val;
}
public boolean isInteger() {
return true;
}
public List<NestedInteger> getList() {
return null;
}
}
static class NestedIntegerListImpl implements NestedInteger {
private List<NestedInteger> list;
public NestedIntegerListImpl(List<NestedInteger> list) {
this.list = new ArrayList<NestedInteger>();
for (NestedInteger ni : list) {
this.list.add(ni);
}
}
return null;
}
public boolean isInteger() {
return false;
}
public List<NestedInteger> getList() {
return list;
}
}
{
// {0,{1,2}, 3 ,{4,{5, 6}}}
List<NestedInteger> l1 = new ArrayList<NestedInteger>();
List<NestedInteger> l2 = new ArrayList<NestedInteger>();
List<NestedInteger> l3 = new ArrayList<NestedInteger>();
List<NestedInteger> l4 = new ArrayList<NestedInteger>();
l4.add(new NestedIntegerImpl(5));
l4.add(new NestedIntegerImpl(6));
l3.add(new NestedIntegerImpl(4));
l3.add(new NestedIntegerListImpl(l4));
l2.add(new NestedIntegerImpl(1));
l2.add(new NestedIntegerImpl(2));
l1.add(new NestedIntegerImpl(0));
l1.add(new NestedIntegerListImpl(l2));
l1.add(new NestedIntegerImpl(3));
l1.add(new NestedIntegerListImpl(l3));
NestedIntegerIterator it1 = new NestedIntegerIterator(l1);
while(it1.hasNext()) {
System.
out.
println(it1.
next()); }
NestedIntegerIterator it2 = new NestedIntegerIterator(l2);
while(it2.hasNext()) {
System.
out.
println(it2.
next()); }
}
}