go数组实现环形队列

package main

import (
	"errors"
	"fmt"
	"os"
)

// CircleQueue 环形队列
type CircleQueue struct {
	maxSize int
	arr     [5]int
	head    int // 队首
	tail    int // 队尾
}

func main() {
	queue := CircleQueue{
		maxSize: 5,
		arr:     [5]int{},
		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)
			} else {
				fmt.Println("添加成功")
			}
		case "get":
			val, err := queue.Pop()
			if err != nil {
				fmt.Println(err.Error())
			}
			fmt.Printf("取出一个数 %d\n", val)

		case "show":
			queue.Show()

		case "exit":
			os.Exit(0)
		}

	}

}
func (q *CircleQueue) Push(val int) error {
	if q.IsFull() {
		return errors.New("队列已满")
	}

	// tail 在队列尾部 但是不包含最后的元素
	q.arr[q.tail] = val
	q.tail = (q.tail + 1) % q.maxSize

	return nil
}

func (q *CircleQueue) Pop() (int, error) {
	if q.IsEmpty() {
		return 0, errors.New("队列为空")
	}
	// head指向队首 并且包含队首元素
	val := q.arr[q.head]
	q.head = (q.head + 1) % q.maxSize
	return val, nil
}

// IsEmpty  队列是否为空
func (q *CircleQueue) IsEmpty() bool {
	return q.tail == q.head
}

func (q *CircleQueue) IsFull() bool {
	return (q.tail+1)%q.maxSize == q.head
}

func (q *CircleQueue) Size() int {
	return (q.tail + q.maxSize - q.head) % q.maxSize
}

func (q *CircleQueue) Show() {
	fmt.Println("环形队列情况如下 ",q.head,q.tail)
	size := q.Size()
	if size == 0 {
		fmt.Println("队列为空")
	}
	tempHead := q.head
	for i := 0; i < size; i++ {
		fmt.Printf("arr[%d]=%d\n", tempHead, q.arr[tempHead])
		tempHead = (tempHead + 1) % q.maxSize
	}
}

 

posted @ 2021-10-03 14:52  brady-wang  阅读(63)  评论(0编辑  收藏  举报