forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeekingIterator.java
47 lines (37 loc) · 1004 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
40
41
42
43
44
45
46
47
// @saorav21994
// TC : O(1)
// SC : O(1)
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private Integer next;
private Iterator<Integer> itr;
private boolean end = false;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
itr = iterator;
traverse();
}
// 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 res = next;
traverse();
return res;
}
@Override
public boolean hasNext() {
return !end;
}
public void traverse() {
if (itr.hasNext() == true) {
next = itr.next();
}
else { end = true; }
}
}