golang array queue

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45604257/article/details/102721582

Description Title:
implement a queue, it has queues, the queue functions like queue element view.
Introduction queue:
queue is an ordered list, you can use an array or a linked list to achieve.
Follow the FIFO principle, that is first stored in the data queue, first removed. After the deposit after going out.
Array achieved
Here Insert Picture Description
rear is the last queue (including the last)
Front is the front of the queue elements (excluding)
code is as follows:

package main

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

//使用一个结构体管理队列
type Queue struct {
	maxSize int
	array   [5]int //数组--》模拟队列
	front   int    //表示指向队列首部
	rear    int    //表示指向队列的尾部
}

//添加数据到队列
func (this *Queue) AddQueue(val int) (err error) {
	//先判断队列是否已满
	if this.rear == this.maxSize-1 { //重要重要:rear是队列尾部含队尾,
		return errors.New("queue full")
	}
	this.rear++ //rear 后移
	this.array[this.rear] = val
	return
}

//从队列中取出数据
func (this *Queue) GetQueue() (val int, err error) {
	//先判断队列是否为空
	if this.rear == this.front { //队列为空
		return -1, errors.New("队列为空")
	}
	this.front++ //front指向队首前面一个,不含队首
	val = this.array[this.front]
	return val, err
}

//显示队列,找到队首,然后遍历到队尾
func (this *Queue) ShowQueue() {
	fmt.Println("队列当前的情况是")
	//front指向队首前面一个,不含队首
	for i := this.front + 1; i <= this.rear; i++ {
		fmt.Printf("array[%d]=%d\t", i, this.array[i])
	}
	fmt.Println()
}

//编写一个主函数测试
func main() {

	//先创建一个队列
	queue := &Queue{
		maxSize: 5,
		front:   -1,
		rear:    -1,
	}
	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.AddQueue(val)
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println("加入队列OK")

			}
		case "get":
			val, err := queue.GetQueue()
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println("从队列中取出了", val)
			}

			fmt.Println("get")
		case "show":
			queue.ShowQueue()
		case "exit":
			os.Exit(0)

		}
	}
}

Disadvantages: This method is the space above the front half portion of a queue can not use the array, the array need to solve the problem as an annular space (circular queue). For details, see the link golang array to achieve circular queue

Guess you like

Origin blog.csdn.net/weixin_45604257/article/details/102721582