golang实现循环队列

思路: 基于数组实现。当容量为k时,我们初始化一个容量为k+1的数组arr,方便区分队列空和满。
当rear==front时,判断队列为空;
当(rear+1) % len(arr) == front时,判断队列为满;

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
}

相关推荐

  1. golang实现循环队列

    2024-03-20 14:04:01       20 阅读
  2. golang实现循环队列

    2024-03-20 14:04:01       8 阅读
  3. rust实现循环队列

    2024-03-20 14:04:01       20 阅读
  4. 循环队列实现(python)

    2024-03-20 14:04:01       18 阅读
  5. Golang实现简单队列(Queue)数据结构

    2024-03-20 14:04:01       34 阅读
  6. Golang实现 NATS JetStream 队列

    2024-03-20 14:04:01       23 阅读
  7. 数组实现循环队列(新增一个空间)

    2024-03-20 14:04:01       46 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-20 14:04:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-20 14:04:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-20 14:04:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-20 14:04:01       20 阅读

热门阅读

  1. 蓝桥杯每日一题:接龙数列

    2024-03-20 14:04:01       15 阅读
  2. 关于Grok的一些看法

    2024-03-20 14:04:01       23 阅读
  3. node.js常用命令及介绍

    2024-03-20 14:04:01       19 阅读
  4. C#中的值类型和引用类型

    2024-03-20 14:04:01       21 阅读
  5. vue3后台管理系统权限路由的实现

    2024-03-20 14:04:01       18 阅读
  6. 北京机器人展2024世界机器人大会

    2024-03-20 14:04:01       18 阅读
  7. Redux 的工作流程

    2024-03-20 14:04:01       20 阅读
  8. LeetCode 热题100 贪心算法专题解析

    2024-03-20 14:04:01       21 阅读