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
}
相关推荐
岁忧41 分钟前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_78943 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
Nejosi_念旧1 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨1 小时前
GO 启动 简单服务
开发语言·后端·golang
小明的小名叫小明1 小时前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
光影少年1 小时前
从前端转go开发的学习路线
前端·学习·golang
斯普信专业组1 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang
秋说3 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy3 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特5 小时前
每日mysql
数据结构·算法