golang实现循环队列

思路 : 基于数组实现。当容量为k时,我们初始化一个容量为k+1的数组arr,方便区分队列空和满。

当rear==front时,判断队列为空;

当(rear+1) % len(arr) == front时,判断队列为满;

go 复制代码
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
}
相关推荐
会员源码网12 小时前
使用`mysql_*`废弃函数(PHP7+完全移除,导致代码无法运行)
后端·算法
木心月转码ing13 小时前
Hot100-Day10-T438T438找到字符串中所有字母异位词
算法
HelloReader14 小时前
Wi-Fi CSI 感知技术用无线信号“看见“室内的人
算法
颜酱17 小时前
二叉树分解问题思路解题模式
javascript·后端·算法
qianpeng89718 小时前
水声匹配场定位原理及实验
算法
董董灿是个攻城狮1 天前
AI视觉连载8:传统 CV 之边缘检测
算法
AI软著研究员2 天前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish2 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
颜酱2 天前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
地平线开发者2 天前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶