type MyCircularQueue struct {
CQ []int
f int
r int
l int
}
//该队列总共存储k个元素
//多申请一个存储空间,用于判断队列空和满的条件 也就是数组总长度为k+1
func Constructor(k int) MyCircularQueue {
CQ := make([]int, k+1, k+1)
var MyCircularQueue = MyCircularQueue{CQ: CQ, l: k+1}
return MyCircularQueue
}
func (this *MyCircularQueue) EnQueue(value int) bool {
if (this.r+1)%this.l == this.f { //队列满的条件
return false
}
this.CQ[this.r] = value
this.r+=1
this.r%=this.l //不要忘记取余循环
return true
}
func (this *MyCircularQueue) DeQueue() bool {
if this.r == this.f {
return false
}
this.CQ[this.f] = 0
this.f+=1
this.f%=this.l//不要忘记取余循环
return true
}
func (this *MyCircularQueue) Front() int {
if this.r == this.f {
return -1
} else {
return this.CQ[this.f]
}
}
func (this *MyCircularQueue) Rear() int {
if this.r == this.f {
return -1
} else {
return this.CQ[(this.r - 1 + this.l)% this.l]//注意点
}
}
func (this *MyCircularQueue) IsEmpty() bool {
if this.r == this.f {
return true
}else {
return false
}
}
func (this *MyCircularQueue) IsFull() bool {
if (this.r+1)%this.l == this.f {
return true
}else {
return false
}
}
go语言实现循环队列----数组实现
最新推荐文章于 2024-06-17 00:00:00 发布