题目:
题解:
java
class PeekingIterator<E> implements Iterator<E> {
private Iterator<E> iterator;
private E nextElement;
public PeekingIterator(Iterator<E> iterator) {
this.iterator = iterator;
nextElement = iterator.next();
}
public E peek() {
return nextElement;
}
@Override
public E next() {
E ret = nextElement;
nextElement = iterator.hasNext() ? iterator.next() : null;
return ret;
}
@Override
public boolean hasNext() {
return nextElement != null;
}
}