LeetCode 284. 【Java】284. Peeking Iterator
原题链接
中等
作者:
tt2767
,
2020-02-25 00:06:47
,
所有人可见
,
阅读 913
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> it;
private Integer peekedValue;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.it = iterator;
this.peekedValue = null;
}
// Returns the next element in the iteration without advancing the iterator.
// 缓存下一次的值并返回
public Integer peek() {
if (this.peekedValue == null && it.hasNext()){
this.peekedValue = it.next();
}
return this.peekedValue;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
// 如果peeked存在,说明原迭代器已经走了一步,直接返回peeked值并置空, 保证操作幂等
@Override
public Integer next() {
if (this.peekedValue != null){
Integer res = this.peekedValue;
this.peekedValue = null;
return res;
}
return this.it.next();
}
// 如果存在peeked缓存则说明至少还有一个
// 不存在peeked缓存时与原it一致
@Override
public boolean hasNext() {
return this.peekedValue != null || this.it.hasNext();
}
}