golang实现循环队列

package main import ( "fmt" ) type MyCircularQueue struct { rear, front int data []int capacity 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] = value this.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)) // 返回 true fmt.Println(circularQueue.EnQueue(2)) // 返回 true fmt.Println(circularQueue.EnQueue(3)) // 返回 true fmt.Println(circularQueue.EnQueue(4)) // 返回 false,队列已满 fmt.Println(circularQueue.Rear()) // 返回 3 fmt.Println(circularQueue.IsFull()) // 返回 true fmt.Println(circularQueue.DeQueue()) // 返回 true fmt.Println(circularQueue.EnQueue(4)) // 返回 true fmt.Println(circularQueue.Rear()) // 返回 4 }
上一篇:3月19日做题


下一篇:虚拟DOM是什么以及React 和Vue中有何区别