-
Notifications
You must be signed in to change notification settings - Fork 2
/
ArrayQueue.go
68 lines (57 loc) · 1.38 KB
/
ArrayQueue.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package Queues
type circArrQ[T any] struct {
sz, head, tail uint
content []T
}
func MakeArrayQueue[T any](initCap uint) ArrayQueue[T] {
return &circArrQ[T]{0, 0, 0, make([]T, initCap)}
}
func (this circArrQ[T]) Empty() bool {
return this.sz == 0
}
func (this *circArrQ[T]) resize(newLen uint) {
nc := make([]T, newLen)
if this.head < this.tail {
copy(nc, this.content[this.head:this.tail])
} else {
copy(nc, this.content[this.head:])
copy(nc[uint(len(this.content))-this.head:], this.content[:this.tail])
this.head, this.tail = 0, this.sz
}
this.content = nc
}
func (this *circArrQ[T]) Shrink() {
this.resize(this.sz | 1)
}
func (this *circArrQ[T]) Clear() {
this.tail, this.head, this.sz = 0, 0, 0
}
func (this circArrQ[T]) Size() uint {
return this.sz
}
func (this *circArrQ[T]) Push(item T) {
if this.sz == uint(len(this.content)) {
this.resize(this.sz * 3 / 2)
}
this.content[this.tail] = item
this.tail = (this.tail + 1) % uint(len(this.content))
this.sz++
}
func (this *circArrQ[T]) Pop() (item T, e error) {
if this.Empty() {
return *new(T), &EmptyQueueError{}
} else {
t := this.content[this.head]
this.content[this.head] = *new(T)
this.head = (this.head + 1) % uint(len(this.content))
this.sz--
return t, nil
}
}
func (this circArrQ[T]) Peek() (item T) {
if this.Empty() {
return *new(T)
} else {
return this.content[this.head]
}
}