目录
一、模拟队列
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()
}
}
}