结构设计
type MyCircularQueue struct {
Queue []int
front int //头指针
rear int //指向尾指针后面一个
Lenth int //队列长度
}
构造
func Constructor(k int) MyCircularQueue {
q := MyCircularQueue{make([]int, k+1), 0, 0, k + 1}
return q
}
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
func (this *MyCircularQueue) EnQueue(value int) bool {
if this.IsFull() {
return false
}
this.Queue[this.rear] = value
this.rear = (this.rear + 1) % this.Lenth
return true
}
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
func (this *MyCircularQueue) DeQueue() bool {
if this.IsEmpty() {
return false
}
this.front = (this.front + 1) % this.Lenth
return true
}
Front: 从队首获取元素。如果队列为空,返回 -1 。
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.Queue[this.front]
}
Rear: 获取队尾元素。如果队列为空,返回 -1 。
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.Queue[(this.rear-1+this.Lenth)%this.Lenth]
}
isEmpty(): 检查循环队列是否为空。
func (this *MyCircularQueue) IsEmpty() bool {
if this.front == this.rear {
return true
}
return false
}
isFull(): 检查循环队列是否已满。
func (this *MyCircularQueue) IsFull() bool {
if (this.rear+1)%this.Lenth == this.front {
return true
}
return false
}