-
Notifications
You must be signed in to change notification settings - Fork 2
/
circular_queue.go
64 lines (55 loc) · 1.11 KB
/
circular_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
package go_circular_queue
type CircularQueue struct {
length int
front int
rear int
arr []interface{}
}
func NewCircularQueue(size int) *CircularQueue {
return &CircularQueue{
length: 0,
front: 0,
rear: -1,
arr: make([]interface{}, size),
}
}
func (q *CircularQueue) Enqueue(value interface{}) bool {
if q.IsFull() {
return false
}
q.rear = (q.rear + 1) % len(q.arr)
q.arr[q.rear] = value
q.length++
return true
}
func (q *CircularQueue) Dequeue() (val interface{}, ok bool) {
if q.IsEmpty() {
return nil,false
}
val = q.arr[q.front]
q.arr[q.front] = nil
q.front = (q.front + 1) % len(q.arr)
q.length--
return val, true
}
func (q *CircularQueue) Front() (val interface{}, ok bool) {
if q.IsEmpty() {
return nil, false
}
return q.arr[q.front], true
}
func (q *CircularQueue) Rear() (val interface{}, ok bool) {
if q.IsEmpty() {
return nil, false
}
return q.arr[q.rear], true
}
func (q *CircularQueue) IsEmpty() bool {
return q.length == 0
}
func (q *CircularQueue) IsFull() bool {
return q.length == len(q.arr)
}
func (q *CircularQueue) Size() int {
return len(q.arr)
}