思路: 基于数组实现。当容量为k时,我们初始化一个容量为k+1的数组arr,方便区分队列空和满。
当rear==front时,判断队列为空;
当(rear+1) % len(arr) == front时,判断队列为满;
package mainimport ("fmt"
)type MyCircularQueue struct {rear, front intdata []intcapacity int
}func MyCircularQueueConstructor(k int) MyCircularQueue {return MyCircularQueue{rear: 0,front: 0,capacity: k,data: make([]int, k+1),}
}func (this *MyCircularQueue) EnQueue(value int) bool {if this.IsFull() {return false}this.data[this.rear] = valuethis.rear = (this.rear + 1) % (this.capacity + 1)return true
}func (this *MyCircularQueue) DeQueue() bool {if this.IsEmpty() {return false}this.front = (this.front + 1) % (this.capacity + 1)return true
}func (this *MyCircularQueue) Front() int {if this.IsEmpty() {return -1}return this.data[this.front]
}func (this *MyCircularQueue) Rear() int {if this.IsEmpty() {return -1}return this.data[(this.rear+this.capacity)%(this.capacity+1)]
}func (this *MyCircularQueue) IsEmpty() bool {return this.rear == this.front
}func (this *MyCircularQueue) IsFull() bool {return ((this.rear + 1) % (this.capacity + 1)) == this.front
}func main() {circularQueue := MyCircularQueueConstructor(3)fmt.Println(circularQueue.EnQueue(1)) // 返回 truefmt.Println(circularQueue.EnQueue(2)) // 返回 truefmt.Println(circularQueue.EnQueue(3)) // 返回 truefmt.Println(circularQueue.EnQueue(4)) // 返回 false,队列已满fmt.Println(circularQueue.Rear()) // 返回 3fmt.Println(circularQueue.IsFull()) // 返回 truefmt.Println(circularQueue.DeQueue()) // 返回 truefmt.Println(circularQueue.EnQueue(4)) // 返回 truefmt.Println(circularQueue.Rear()) // 返回 4
}