g0201_0300.s0284_peeking_iterator.PeekingIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java17 Show documentation
Show all versions of leetcode-in-java17 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
package g0201_0300.s0284_peeking_iterator;
// #Medium #Array #Design #Iterator
import java.util.Iterator;
public class PeekingIterator implements Iterator {
private Iterator it;
private Integer current;
public PeekingIterator(Iterator iterator) {
// initialize any member here.
it = iterator;
current = it.next();
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (current == null) {
current = it.next();
}
return current;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer temp = current;
current = it.hasNext() ? it.next() : null;
return temp;
}
@Override
public boolean hasNext() {
return current != null;
}
}