-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy patharray_queue.go
More file actions
84 lines (69 loc) · 1.43 KB
/
array_queue.go
File metadata and controls
84 lines (69 loc) · 1.43 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package array_queue
import (
"errors"
"fmt"
)
//队列实现(基于数组)
var (
ErrQueueFull = errors.New("error: queue is full")
ErrQueueEmpty = errors.New("error: queue is empty")
)
type ArrayQueue struct {
data []interface{}
head int
tail int
size int
capacity int
}
func New(capacity int) *ArrayQueue {
return &ArrayQueue{
size: 0, head: 0, tail: 0,
data: make([]interface{}, capacity),
capacity: capacity,
}
}
//入队列
func (queue *ArrayQueue) Enqueue(val interface{}) error {
if queue.tail >= queue.capacity && queue.head == 0 {
return ErrQueueFull
}
if queue.head > 0 {
copy(queue.data[0:], queue.data[queue.head:])
queue.tail -= queue.head
queue.head = 0
}
queue.data[queue.tail] = val
queue.size++
queue.tail++
return nil
}
//出队列
func (queue *ArrayQueue) Dequeue() (interface{}, error) {
if queue.Empty() {
return nil, ErrQueueEmpty
}
res := queue.data[queue.head]
queue.size--
queue.head++
return res, nil
}
//队头元素
func (queue *ArrayQueue) Front() interface{} {
return queue.data[queue.head]
}
//队尾元素
func (queue *ArrayQueue) Back() interface{} {
return queue.data[queue.tail-1]
}
func (queue *ArrayQueue) Empty() bool {
return queue.size <= 0
}
func (queue *ArrayQueue) Size() int {
return queue.size
}
func (queue *ArrayQueue) PrintData() {
for i := queue.head; i < queue.tail; i++ {
fmt.Print(queue.data[i], " ")
}
fmt.Println()
}