1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator implements Iterator<Integer> {
private Integer top;
private Iterator<Integer> iterator;

public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iterator = iterator;
if (this.iterator.hasNext()) {
top = this.iterator.next();
}
}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return top;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer ans = top;
if (this.iterator.hasNext()) {
top = this.iterator.next();
} else {
top = null;
}
return ans;
}

@Override
public boolean hasNext() {
return top != null;
}
}

把这个抽象为给枪上子弹. 枪管里只能有一颗子弹, 弹匣里可以有很多. peek()就是看枪膛里的子弹是什么, next()则是看枪膛的子弹是什么, 发射这个子弹并且再次填装. hasNext()是看枪膛中有没有子弹.

这里的top就表示枪膛里的子弹. next()的话就是首先记录枪膛的子弹是什么, 然后看弹匣中还有子弹吗(iterator.hasNext()), 如果有那就让top等于iterator.next(), 没有就让top等于null. 然后我们通过判断top的值来确实hasNext()返回什么.

时间复杂度和空间复杂度都是O(1).