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
}
相关推荐
放下华子我只抽RuiKe52 分钟前
机器学习全景指南-探索篇——发现数据内在结构的聚类算法
人工智能·深度学习·算法·机器学习·语言模型·数据挖掘·聚类
Yupureki16 分钟前
《C++实战项目-高并发内存池》3.ThreadCache构造
服务器·c语言·c++·算法·哈希算法
j_xxx404_21 分钟前
C++算法:一维/二维前缀和算法模板题
开发语言·数据结构·c++·算法
x_xbx24 分钟前
LeetCode:111. 二叉树的最小深度
算法·leetcode·职场和发展
入目星河滚烫31 分钟前
网易互娱2020校招在线笔试—游戏研发第一批—游泳池-研发
算法·笔试·数据结构与算法
xier_ran34 分钟前
【第一周】关键词解释:倒数排名融合(Reciprocal Rank Fusion, RRF)算法
开发语言·python·算法
spiritualfood37 分钟前
蓝桥杯大学b组水质检测
c语言·c++·算法·青少年编程·职场和发展·蓝桥杯
进击的小头1 小时前
第6篇:贝尔曼最优化理论
python·算法·动态规划
EQUINOX11 小时前
bitset + meet in the middle,P3067 [USACO12OPEN] Balanced Cow Subsets G
算法
四处炼丹1 小时前
OpenClaw本地部署与Multi-Agent 技术分享
人工智能·算法·aigc·agent·ai编程