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
}
相关推荐
止语Lab17 小时前
Go跨平台编译的决策树:从\
开发语言·决策树·golang
KaMeidebaby17 小时前
卡梅德生物技术快报|抗体的制备与纯化:分子实验实操:番茄 sHSP 重组表达与抗体的制备与纯化工艺
前端·数据库·人工智能·其他·算法·百度·新浪微博
Kurisu57517 小时前
深度解析:Go 语言 GMP 调度器模型与内核线程探测
java·数据库·golang
Han.miracle17 小时前
Java HashMap 与 ConcurrentHashMap 核心原理总结:从 Hash 冲突到 LongAdder
java·算法·哈希算法
菜菜的顾清寒17 小时前
力扣HOT100(35)回溯-全排列
算法·leetcode·职场和发展
weixin_4684668517 小时前
目标识别算法落地实战:从选型到部署的全流程指南
图像处理·人工智能·python·算法·目标检测·机器视觉·目标识别
MicroTech202517 小时前
微算法科技(NASDAQ :MLGO)量子启发进化算法(QEA)与区块链(BC)集成技术:构建高可靠去中心化创新方案
科技·算法·量子计算
CQU_JIAKE17 小时前
5.27【A】
算法
江屿风17 小时前
C++OJ题经验总结(竞赛)3
开发语言·c++·笔记·算法
手写码匠17 小时前
从零手写 SQL 查询引擎:解析器、优化器与执行器实战
人工智能·深度学习·算法·aigc