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
}
相关推荐
居然有人65434 分钟前
23贪心算法
数据结构·算法·贪心算法
MelonTe1 小时前
使用Go复刻skiplist核心功能
redis·golang
SylviaW081 小时前
python-leetcode 37.翻转二叉树
算法·leetcode·职场和发展
h^hh2 小时前
洛谷 P3405 [USACO16DEC] Cities and States S(详解)c++
开发语言·数据结构·c++·算法·哈希算法
玦尘、2 小时前
位运算实用技巧与LeetCode实战
算法·leetcode·位操作
重生之我要成为代码大佬2 小时前
Python天梯赛10分题-念数字、求整数段和、比较大小、计算阶乘和
开发语言·数据结构·python·算法
Best_Me072 小时前
【CVPR2024-工业异常检测】PromptAD:与只有正常样本的少样本异常检测的学习提示
人工智能·学习·算法·计算机视觉
HBryce242 小时前
缓存-算法
算法·缓存
eso19833 小时前
Spark MLlib使用流程简介
python·算法·spark-ml·推荐算法
夏末秋也凉3 小时前
力扣-回溯-93 复原IP地址
算法·leetcode