Created
August 27, 2014 23:26
-
-
Save shixiaoyu/feaeeb262adcc2113869 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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