package main
import (
"errors"
"fmt"
"os"
)
type CircleQueue struct {
maxSize int
array [5]int
head int
tail int
}
func (this *CircleQueue) Push (val int) (err error){
if this.IsFull() {
return errors.New("已经满了")
}
fmt.Println("加入", val)
this.array[this.tail % this.maxSize] = val
this.tail ++
return
}
func (this *CircleQueue) Pop() (val int, err error) {
if this.IsEmpty() {
return 0, errors.New("为空")
}
val = this.array[this.head % this.maxSize]
this.head ++
return
}
// IsFull 队列shi不是满了
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 (this *CircleQueue) ListQueue() {
size := this.Size()
if size == 0{
fmt.Println("为空")
}
temHEead := this.head
for i:=0;i < size; i++ {
fmt.Printf("arr[%d]=%d\n", temHEead, this.array[temHEead])
temHEead = (temHEead + 1) % this.maxSize
}
}
func main() {
queue := &CircleQueue{
maxSize: 5,
head: 0,
tail: 0,
}
var key string
var val int
for {
fmt.Println("add")
fmt.Println("get")
fmt.Println("show")
fmt.Println("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("加入成功")
}
case "get":
val, err := queue.Pop()
if err != nil{
fmt.Println(err.Error())
}else {
fmt.Println("取出一个数", val)
}
case "show":
queue.ListQueue()
case "exit":
os.Exit(0)
}
}
}