forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
44 lines (39 loc) · 945 Bytes
/
Solution.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
/* 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 {
iter *Iterator
hasPeeked bool
peekedElement int
}
func Constructor(iter *Iterator) *PeekingIterator {
return &PeekingIterator{iter, iter.hasNext(), iter.next()}
}
func (this *PeekingIterator) hasNext() bool {
return this.hasPeeked || this.iter.hasNext()
}
func (this *PeekingIterator) next() int {
if !this.hasPeeked {
return this.iter.next()
}
this.hasPeeked = false
return this.peekedElement
}
func (this *PeekingIterator) peek() int {
if !this.hasPeeked {
this.peekedElement = this.iter.next()
this.hasPeeked = true
}
return this.peekedElement
}