-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeekingIterator.java
69 lines (59 loc) · 1.69 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
// Solution 1:
class PeekingIterator implements Iterator<Integer> {
private Integer ptr;
private Iterator<Integer> it;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
it = iterator;
ptr = it.hasNext()?it.next():null;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return ptr;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer ret = ptr;
ptr = it.hasNext()?it.next():null;
return ret;
}
@Override
public boolean hasNext() {
return (ptr != null);
}
}
//Bad Solution:
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private Integer ptr;
private Iterator<Integer> i;
private Iterator<Integer> k;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
i = iterator;
k = iterator;
ptr = k.hasNext()?k.next():null;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
Integer ret = ptr;
Iterator<Integer> t = i; //It takes a large amount of time here
ptr = t.hasNext()?t.next():null;
return ret;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
return i.next();
}
@Override
public boolean hasNext() {
return i.hasNext();
}
}