题目描述
题目链接
https://leetcode.com/problems/peeking-iterator/
方法思路
题目要求在class Iterator的基础上设计一个class PeekingIterator。主要是增加一个peek()方法。该方法获得和调用next()一样的值,但是迭代器不移动。
给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 – 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
所以只要设置一个缓存位cache用来存储peek()方法返回的值就可以解决问题了。
若cache不为null,则表示调用过了peek()方法,即数组或者说链表中还存在元素
若此时再调用next()方法,则返回的是cache,同时cache置为null。为下一次调用某个成员方法做准备。
Approach1:
class PeekingIterator implements Iterator<Integer> {
//Runtime: 47 ms, faster than 99.35%
//Memory Usage: 36.7 MB, less than 94.95%
private Iterator<Integer> iterator;
private Integer cache = null; // 第一次peek时, 缓存迭代的元素
public PeekingIterator(Iterator<Integer> iter) {
// initialize any member here.
iterator = iter;
}
// Returns the next element in the iteration without advancing the iterator.
// 返回迭代中的下一个元素而不推进迭代器
public Integer peek() {
if (cache == null)
cache = iterator.next();
return cache;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (cache == null)
return iterator.next();
Integer temp = cache;
cache = null;
return temp;
}
@Override
public boolean hasNext() {
return cache != null || iterator.hasNext();
}
}