forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeekingIterator.java
39 lines (32 loc) · 952 Bytes
/
PeekingIterator.java
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
39
import java.util.Iterator;
public class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> mIterator;
private Integer mNext;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
mIterator = iterator;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (mNext != null) {
return mNext;
}
mNext = mIterator.next();
return mNext;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (mNext != null) {
Integer ret = mNext;
mNext = null;
return ret;
}
return mIterator.next();
}
@Override
public boolean hasNext() {
return mNext != null || mIterator.hasNext();
}
}