mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems: add peeking iterator
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
9dc591147a
commit
a71684d500
1 changed files with 32 additions and 0 deletions
32
problems/peeking-iterator.java
Normal file
32
problems/peeking-iterator.java
Normal file
|
@ -0,0 +1,32 @@
|
|||
class PeekingIterator implements Iterator<Integer> {
|
||||
private Iterator<Integer> it;
|
||||
|
||||
private Integer pVal;
|
||||
private boolean pHasNext;
|
||||
|
||||
public PeekingIterator(Iterator<Integer> iterator) {
|
||||
it = iterator;
|
||||
next();
|
||||
}
|
||||
|
||||
public Integer peek() {
|
||||
return pVal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer next() {
|
||||
pHasNext = it.hasNext();
|
||||
|
||||
Integer oldValue = pVal;
|
||||
if (pHasNext) {
|
||||
pVal = it.next();
|
||||
}
|
||||
|
||||
return oldValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return pHasNext;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue