golang 数组模拟环形队列


golang 数组模拟环形队列


1) 使用原因
数组遵循先入后出的原则,且存入取出后本身所含的数据无法移动,照成前面的数据虽然被取出了但后面的数据一但把数组填满,可无法把还需要填的数据放入前面已经把元素取出的数组地址。

2)使用原理
把数组模拟为一个环形队列,首尾相接,并把数组的的最后一个地址空出作为这个环形队列的标记点。

3)代码演示

package main

import (
	"fmt"
	"errors"
	"os"

)

//使用结构体管理环形队列
type CircleQueue struct {
	maxSize int 
	array [5] int 
	head int 
	tail int
}

//入队列 AddQueue(push) GetQueue(pop)
func (this *CircleQueue) Push(val int) (err error) {
    if this.IsFull() {
		return errors.New("queue is full")
	}

	this.array[this.tail] = val //把值给尾部 , this.tail在尾部但不含值
	this.tail = (this.tail + 1) % this.maxSize
	return 
}

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 = (this.head + 1) % this.maxSize
	return

}

//显示队列
func (this *CircleQueue) ListQueue() {
	
	fmt.Println("环形队列情况如下: ")
	//取出当前队列有多少元素
	size := this.Size()
	if size == 0 {
        fmt.Println("队列为空")
	}
	
	tempHead := this.head
	for i := 0; i < size; i++ {
		fmt.Printf("arr[%d]=%d\t", tempHead, this.array[tempHead])
		tempHead = (tempHead + 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 输入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 "eixt":
		        os.Exit(0)

		}
	}  

    
}

猜你喜欢

转载自blog.csdn.net/qq_42665165/article/details/106331279