package main
import (
"errors"
"fmt"
"os"
)
/* 使用一个结构体管理环形队列
思路:
提醒:尾索引的下一个为头索引时表示队列满,即 将队列容量空出一个约定,这个在判断队列满的时候要注意(tail +1 ) % maxSize == head (满)
1. 什么时候队列满 (tail + 1 ) % maxSize == head
2. tail == head 表示空
3. 初始化时,tail = 0 ,head == 0
4. 怎么统计该队列有多少个元素(tail + maxSize - head) % maxSize
*/
// 使用一个结构体管理队列
type CirceleQueue struct {
maxSize int // 4
array [5]int // 数组
head int // 标记指向队列的首部
tail int // 表示指向队列的尾部
}
// 添加数据到队列 入队列
func (this *CirceleQueue) PushQueeu(val int) (err error) {
// 先判断队列是否已满
if this.IsFull(){
return errors.New("queue FULL")
}
// 分析出this.tail 在队列尾部,但是不包含最后一个元素
this.array[this.tail] = val // 把值给尾部
this.tail = (this.tail +1) % this.maxSize
return
}
// 从队列中取出数据 出队列
func (this *CirceleQueue) PopQueue() (val int, err error) {
// 先判断队列是否为空
if this.IsEmpty() {
return 0,errors.New("queue Empty")
}
// 取出数据, head 是指向对首的并且包含对首的元素
val = this.array[this.head]
this.head = (this.head +1) % this.maxSize
return
}
// 判断环形队列是否为满
func (this *CirceleQueue) IsFull() bool {
fmt.Println(this.head)
return (this.tail + 1) % this.maxSize == this.head
}
// 判断环形列表是否为空
func (this *CirceleQueue) IsEmpty() bool {
return this.tail == this.head
}
// 取出环形队列有多少个元素
func (this *CirceleQueue) Size() int {
// 这是一个关键的算法
return (this.tail + this.maxSize - this.head) % this.maxSize
}
// 显示队列
func (this *CirceleQueue) ListQueue() {
fmt.Println("环形队列情况如下...")
// 取出当前队列有多少个元素
size := this.Size()
if size == 0 {
fmt.Println("queue Empty..")
}
// 设计一个辅助变量,指向head
tempHead := this.head
for i := 0; i < size; i++ {
fmt.Printf("arr[%d]=%d\t\n",tempHead,this.array[tempHead])
tempHead = (tempHead + 1 ) % this.maxSize
}
}
// 编写一个主函数测试
func main() {
fmt.Println(1 % 5)
// 先创建一个队列
queue := &CirceleQueue{
maxSize: 5,
head: 0,
tail: 0,
}
var key string
var val int
// 添加数据
for {
fmt.Println("1. 输入push 表示添加数据到队列")
fmt.Println("2. 输入pop 表示从队列获取数据")
fmt.Println("3. 输入show 表示显示队列")
fmt.Println("4. 输入exit 表示退出")
fmt.Scanln(&key)
switch key {
case "push":
fmt.Println("请输入你要入队列的数:")
fmt.Scanln(&val)
err := queue.PushQueeu(val)
if err == nil {
fmt.Println("加入队列ok...")
} else {
fmt.Println(err.Error())
}
case "pop":
val, err := queue.PopQueue()
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("从队列中取出了一个数=",val)
}
case "show":
queue.ListQueue()
case "exit":
os.Exit(0)
}
}
}
Golang 数据结构-环形队列
于 2023-05-14 15:56:30 首次发布