-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
84 lines (66 loc) · 1.73 KB
/
queue.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package arrayqueue
import "fmt"
// Queue is a queue based on a slice.
type Queue struct {
data []interface{}
}
// BufferSize returns the capacity of the queue.
func (queue *Queue) BufferSize() int {
return cap(queue.data)
}
// SetBufferSize sets the capacity of the queue.
func (queue *Queue) SetBufferSize(bufferSize int) error {
if bufferSize < 0 {
return fmt.Errorf(
"buffer size is less than 0: %d", bufferSize)
}
if bufferSize < len(queue.data) {
return fmt.Errorf(
"buffer size is less than the length of the queue: %d",
bufferSize)
}
data := make([]interface{}, len(queue.data), bufferSize)
copy(data, queue.data)
queue.data = data
return nil
}
// Clear removes all the elements from the queue.
func (queue *Queue) Clear() {
queue.data = queue.data[:0]
}
// Length returns the numbers of elements
// in the queue.
func (queue *Queue) Length() int {
return len(queue.data)
}
// Peek returns the last element of
// the queue.
func (queue *Queue) Peek() interface{} {
return queue.data[0]
}
// Enqueue puts the element in the end of the queue.
func (queue *Queue) Enqueue(elem interface{}) {
queue.data = append(queue.data, elem)
}
// Dequeue returns the last element of the queue
// and removes it from the queue.
func (queue *Queue) Dequeue() (interface{}, error) {
if queue.Length() <= 0 {
return nil, fmt.Errorf("the queue has no elements")
}
lastElem := queue.data[0]
queue.data = queue.data[1:]
return lastElem, nil
}
// NewQueue returns a new queue
// based on a slice.
func NewQueue(queueCapacity int) (*Queue, error) {
if queueCapacity < 0 {
return nil, fmt.Errorf(
"negative capacity value: %d", queueCapacity)
}
data := make([]interface{}, 0, queueCapacity)
return &Queue{
data: data,
}, nil
}