-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeeking-iterator.go
54 lines (44 loc) · 929 Bytes
/
peeking-iterator.go
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
package peekingiterator
/* Below is the interface for Iterator, which is already defined for you.
*
* type Iterator struct {
*
* }
*
* func (this *Iterator) hasNext() bool {
* // Returns true if the iteration has more elements.
* }
*
* func (this *Iterator) next() int {
* // Returns the next element in the iteration.
* }
*/
type PeekingIterator struct {
iterator *Iterator
head *int
}
func Constructor(iter *Iterator) *PeekingIterator {
var res PeekingIterator
if iter.hasNext() {
val := iter.next()
res.head = &val
}
res.iterator = iter
return &res
}
func (this *PeekingIterator) hasNext() bool {
return this.head != nil
}
func (this *PeekingIterator) next() int {
res := this.head
if this.iterator.hasNext() {
val := this.iterator.next()
this.head = &val
} else {
this.head = nil
}
return *res
}
func (this *PeekingIterator) peek() int {
return *this.head
}