My code:
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iterator;
private Integer pre;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iterator = iterator;
if (this.iterator.hasNext()) {
pre = this.iterator.next();
}
else
pre = null;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return pre;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer ret = pre;
if (this.iterator.hasNext()) {
pre = this.iterator.next();
}
else {
pre = null;
}
return ret;
}
@Override
public boolean hasNext() {
return pre != null;
}
}
这道题目没什么难度。就是pre 指向当前 next, next往后移动一格。
然后当hasNext 返回false时,pre = null
判断 hasNext, 也特别简单。只用判断 pre == null
Follow up 说能不能把Integer 改成其他任意类型。我的做法是可以的。
Anyway, Good luck, Richardo!
My code:
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
Integer pre = null;
Iterator<Integer> iter;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iter = iterator;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (pre == null) {
pre = iter.next();
}
return pre;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (pre != null) {
Integer temp = pre;
pre = null;
return temp;
}
else {
return iter.next();
}
}
@Override
public boolean hasNext() {
if (pre != null) {
return true;
}
else {
return iter.hasNext();
}
}
}
题目并不难。也可以改成泛型。
reference:
https://github.com/google/guava/blob/703ef758b8621cfbab16814f01ddcc5324bdea33/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java#L1125
Anyway, Good luck, Richardo! -- 09/12/2016