05 August 2008
Given an Iterator class interface with methods:
and 1
next()
, design and implement a PeekingIterator that support the 1
hasNext()
operation – it essentially peek() at the element that will be returned by the next call to next().1
peek()
Example:
1
2
3
4
5
6
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.
Follow up: How would you extend your design to be generic and work with all types, not just integer?
传统的迭代器Iterator主要提供两个方法,next() - 返回当前元素并将索引指向下一个元素;hasNext() - 检查当前元素的下一个元素是否存在;这道题还需要加一个方法peek() - 返回当前元素但不移动索引;做法比较简单直接。
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> {
Integer next;
Iterator<Integer> iter;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
iter = iterator;//类变量“迭代器”等于传进来的值
if (iter.hasNext()) { //类变量元素等于当前元素
next = iter.next();
}
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return next; //不移动索引,直接返回当前元素
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer temp = next;
// next有两种情况需要处理下
if (iter.hasNext()) {
next = iter.next(); //从当前元素指向下一个元素
} else {
next = null;
}
return temp;
}
@Override
public boolean hasNext() {
return next != null;
}
}
Follow up 范型例子