复制 package main import ( "errors" "fmt" "os" ) type CircleQueue struct { maxSize int array [5]int head int tail int } //添加队列 func (c *CircleQueue) Push(val int) (err error) { //先判断队列是否已满 if c.IsFull() { return errors.New("queue full") } c.array[c.tail] = val c.tail = (c.tail + 1) % c.maxSize return } //取出队列 func (c *CircleQueue) Pop() (val int, err error) { //先判断队列是否为空 if c.IsEmpty() { return 0, errors.New("queue empty") } val = c.array[c.head] c.head = (c.head + 1) % c.maxSize return val, err } //判断环形队列为空 func (c *CircleQueue) IsEmpty() bool { return c.head == c.tail } //判断环形队列满了 func (c *CircleQueue) IsFull() bool { return (c.tail+1)%c.maxSize == c.head } //环形队列的数目 func (c *CircleQueue) Size() int { return (c.tail + c.maxSize - c.head) % c.maxSize } //显示队列 func (c *CircleQueue) ListQueue() { fmt.Println("环形队列情况如下:") size := c.Size() if size == 0 { fmt.Println("队列为空") return } tempHead := c.head for i := 0; i < size; i++ { fmt.Printf("array[%d]=%d\n", tempHead, c.array[tempHead]) tempHead = (tempHead + 1) % c.maxSize } fmt.Println() } func main() { var key string var val int queue := &CircleQueue{ maxSize: 5, head: 0, tail: 0, } //添加数据 for { fmt.Println("\n1.输入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.Println("从队列取出一个数=", val) } case "show": queue.ListQueue() case "exit": os.Exit(0) } } }
标签:head,err,val,队列,fmt,列表,Println,Go From: https://www.cnblogs.com/wuchangblog/p/16704101.html