题目本身很简单,就是实现一个支持 peek 操作的迭代器。
Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().
Example:
Assume that the iterator is initialized to the beginning of the list: [1,2,3].
Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
You call next() the final time and it returns 3, the last element.
Calling hasNext() after that should return false.
我的实现:
class PeekingIterator implements Iterator<Integer> {
private final Iterator<Integer> iterator;
private Integer value;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
this.value = null;
}
public Integer peek() {
if (value != null) return value;
value = iterator.next();
return value;
}
@Override
public boolean hasNext() {
return value != null || iterator.hasNext();
}
@Override
public Integer next() {
Integer temp;
if (value != null) {
temp = value;
value = null;
} else {
temp = iterator.next();
}
return temp;
}
}
Runtime 是 93.72%
iterator 去掉 final 修饰,value 不在 Constructor 中赋值 null,Runtime 就变为 100.00% 了。
public class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iterator;
private Integer value = null;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
}
......
}