循环队列:
通常:index = i 的后一个是index+1
index = i 的前一个是index+1
但是这里的循环队列,我们将使用取模运算技巧
index = i 的后一个是(index + 1) % capacity
index = i 的前一个是(index - 1 +capacity) % capacity
package main
import "fmt"
type Queue struct {
Size int
Q []int
Front int // 前指针
Rear int // 尾指针
}
func main() {
q := CreateQueue(5)
fmt.Println(q.IsEmpty())
q.Push(2)
q.Push(5)
q.Push(8)
q.Push(9)
fmt.Println(q.Q)
var val int
q.Pop(&val)
fmt.Println(val)
q.Push(13)
q.Push(15)
q.Push(16)
fmt.Println(q.Q)
}
// 创建一个循环队列, 初始化队列
func CreateQueue(size int) *Queue {
q := &Queue{}
q.Size = size
q.Front = 0
q.Rear = 0
q.Q = make([]int, size+1)
return q
}
//判断队列是否空
func (q *Queue) IsEmpty() bool {
if q.Front != q.Rear {
return false
}
return true
}
//判断队列是否满
func (q *Queue) IsFull() bool {
if q.Front == (q.Rear+1)%(q.Size+1) {
return true
}
return false
}
// 向队列添加元素
func (q *Queue) Push(i int) bool {
if q.IsFull() {
return false
}
q.Q[q.Rear] = i
q.Rear = (q.Rear + 1) % (q.Size + 1)
return true
}
// 向队列添加元素
func (q *Queue) Pop(val *int) bool {
if q.IsEmpty() {
return false
}
val = &q.Q[q.Front]
q.Q[q.Front] = 0
q.Front = (q.Front + 1) % (q.Size + 1)
return true
}