go 用数组模拟队列,环行队列

本文介绍如何使用Go语言中的数组来实现简单的队列和环形队列数据结构。通过具体的代码示例展示了队列的基本操作,如添加、删除元素及判断队列是否为空或满等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、模拟队列

二、环行队列


一、模拟队列

package main

import (
	"errors"
	"fmt"
)

type singleQueue struct {
	maxsize int
	array [5]int
	front int
	rear int
}

// 添加队列
func (this *singleQueue) AddSingle(val int) error{
	if this.rear == this.maxsize-1{
		return errors.New("singque is full")
	}
	this.rear++
	this.array[this.rear] = val
	return nil
}

// 显示队列
func (this *singleQueue) ShowSingle(){
	for i:=this.front+1;i<=this.rear ;i++  {
		fmt.Printf("array[%d]=%d\n",i,this.array[i])
	}
}

// 删除队列元素
func (this *singleQueue) DeleteSingle()(int,error){
	if this.front == this.rear{
		return -1,errors.New("singleQueue is empty")
	}
	this.front++
	return this.array[this.front],nil
}


func main(){
	singleQueue:=singleQueue{
		maxsize:5,
		front:-1,
		rear:-1,
	}
	err:=singleQueue.AddSingle(4)
	if err!=nil{
		fmt.Printf("%s",err)
	}else{

	}
}

二、环行队列

package main

import (
	"errors"
	"fmt"
)

type circleQueue struct {
	maxsize int
	array [5]int
	head int
	tail int
}

// 环形队列的添加
func (this *circleQueue)Push(val int) error{
	if (this.IsFull()){
		return errors.New("queue is full")
	}
	this.array[this.tail] = val
	this.tail = (this.tail+1)%this.maxsize
	return nil
}

// 环形队列的弹出
func (this *circleQueue)Pop() (int,error){
	if (this.IsEmpty()){
		return -1,errors.New("queue is empty")
	}
	val:=this.array[this.head]
	this.head = (this.head+1)%this.maxsize
	return val,nil
}

func (this *circleQueue)Show(){

	index:= this.head
	for i:=0;i<this.Size() ;i++  {
		fmt.Printf("%d \t ",this.array[index])
		index = (index+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.head == this.tail
}

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("add 是添加队列")
		fmt.Println("pop 式弹出队列")
		fmt.Println("show 是显示队列")
		fmt.Scanln(&key)
		switch key {
		case "add":
			fmt.Println("请输入值:")
			fmt.Scanln(&val)
			err:=queue.Push(val)
			if err!=nil{
				fmt.Printf("%s",err)
			}
			fmt.Println()
		case "pop":
			val,err:=queue.Pop()
			if err!=nil{
				fmt.Printf("%s",err)
			}
			fmt.Printf(" 值式:%d",val)
			fmt.Println()
		case "show":
			queue.Show()
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值