Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created August 27, 2014 23:26
Show Gist options
  • Save shixiaoyu/feaeeb262adcc2113869 to your computer and use it in GitHub Desktop.
Save shixiaoyu/feaeeb262adcc2113869 to your computer and use it in GitHub Desktop.
public class DeepIterator implements Iterator<Integer> {
private Stack<Iterator> iteratorStack = new Stack<Iterator>();
private Integer top = null;
public DeepIterator(Iterable iterable){
this.iteratorStack.push(iterable.iterator());
}
@Override
public boolean hasNext() {
if(this.top != null) return true;
while(!this.iteratorStack.isEmpty()) {
Iterator tmpIterator = this.iteratorStack.peek();
if(tmpIterator.hasNext()){
Object tmp = tmpIterator.next();
if(tmp instanceof Integer){
this.top = (Integer) tmp;
return true;
} else if(tmp instanceof Iterable){
this.iteratorStack.push(((Iterable) tmp).iterator());
} else {
throw new RuntimeException("Unsupported data type. ");
}
} else {
this.iteratorStack.pop();
}
}
return false;
}
@Override
public Integer next() throws NoSuchElementException {
if(hasNext()){
Integer tmp = this.top;
this.top = null;
return tmp;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("This is not supported right now.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment