package main
import ("fmt"
"os"
"errors"
)
// 使用结构体管理环形队列
type CircleQueue struct{
maxSize int
array [5]int
head int //指向队列队首
tail int //指向队列队尾
}
// 入队列Push
func (this *CircleQueue)Push(val int) (err error){
if this.IsFull(){
return errors.New("queue full")
}
// this.tail在队列尾部,但不包含最后的元素
this.array[this.tail] = val //把值给尾部
this.tail ++
return
}
// 出队列Pop
func (this *CircleQueue)Pop()(val int,err error){
if this.IsEmpty() {
return 0, errors.New("queue empty")
}
// 取出,head指向队首,并且含队首元素
val = this.array[this.head]
this.head++
return
}
// 显示队列
func (this *CircleQueue)Show(){
fmt.Println("环形队列情况如下")
// 取出当前队列有多少个元素
size := this.Size()
if size == 0{
fmt.Println("队列为空")
}
// 设计一个辅助变量
thempHead := this.head
for i :=0; i < size; i ++{
fmt.Printf("arr[%d] = %d\t", thempHead, this.array[i])
thempHead = (thempHead + 1) % this.maxSize
}
fmt.Println()
}
// 判断环形队列为满
func (this *CircleQueue) IsFull() bool{
return (this.tail + 1) % this.maxSize == this.head
}
// 判断环形队列是否为空
func (this *CircleQueue) IsEmpty() bool{
return this.tail == this.head
}
// 取出环形队列有多少个元素
func (this *CircleQueue) Size()int{
return (this.tail + this.maxSize - this.head) % this.maxSize
}
func main() {
// 初始化一个环形队列
queue := &CircleQueue{
maxSize : 5,
head : 0,
tail : 0,
}
var key string
var val int
for {
fmt.Println("1. 输入add表示添加数据到队列")
fmt.Println("2. 输入get获取队列中的数值")
fmt.Println("3. 输入show表示查看队列")
fmt.Println("4. 输入exit表示退出程序")
fmt.Scanln(&key)
switch key{
case "add":
fmt.Println("请输入你要入队列数")
fmt.Scanln(&val)
err := queue.Push(val)
if err != nil{
fmt.Println(err.Error())
}else{
fmt.Println("入队列ok")
}
case "get":
val, err := queue.Pop()
if err != nil{
fmt.Println(err.Error())
}else{
fmt.Print("从队列中获取一个数=", val)
}
case "show" :
queue.Show()
case "exit":
os.Exit(0)
}
}
}