Description
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
1 | Assume that the iterator is initialized to the beginning of the list: [1,2,3]. |
Follow up: How would you extend your design to be generic and work with all types, not just integer?
Solution
1 | // Java Iterator interface reference: |
Method 2, more better1
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
39
40
41
42
43import java.util.NoSuchElementException;
class PeekingIterator implements Iterator<Integer> {
Integer next;
Iterator<Integer> iter;
boolean noSuchElement;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
iter = iterator;
advanceIter();
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
// you should confirm with interviewer what to return/throw
// if there are no more values
return next;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
public Integer next() {
if (noSuchElement)
throw new NoSuchElementException();
Integer res = next;
advanceIter();
return res;
}
public boolean hasNext() {
return !noSuchElement;
}
private void advanceIter() {
if (iter.hasNext()) {
next = iter.next();
} else {
noSuchElement = true;
}
}
}