-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeeking-iterator.go
51 lines (45 loc) · 1 KB
/
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
/* 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.
* }
*/
package main
// 284 https://leetcode-cn.com/problems/peeking-iterator/
// 迭代器
type PeekingIterator struct {
iter *Iterator
cache []int
}
func Constructor(iter *Iterator) *PeekingIterator {
return &PeekingIterator{iter: iter}
}
func (this *PeekingIterator) hasNext() bool {
if len(this.cache) > 0 {
return true
}
return this.iter.hasNext()
}
func (this *PeekingIterator) next() int {
if len(this.cache) > 0 {
ans := this.cache[0]
this.cache = this.cache[1:]
return ans
}
return this.iter.next()
}
func (this *PeekingIterator) peek() int {
if len(this.cache) > 0 {
return this.cache[0]
}
this.cache = append(this.cache, this.iter.next())
return this.cache[0]
}