1 package main
2
3 import (
4 "fmt"
5 "errors"
6 "os"
7 )
8
9 //管理环形队列的结构
10 type Queue struct {
11 maxSize int
12 array [5]int
13 head int
14 tail int
15 }
16
17 //入队列
18 func (this *Queue) Push(val int) (err error) {
19 if this.IsFull() {
20 return errors.New("队列已满!")
21 }
22 this.array[this.tail] = val
23 this.tail = (this.tail + 1) % this.maxSize
24 return
25 }
26
27 //出队列
28 func (this *Queue) Pop() (val int, err error) {
29 if this.IsEmpty() {
30 return 0, errors.New("队列为空!")
31 }
32 val = this.array[this.head]
33 this.head = (this.head + 1) % this.maxSize
34 return
35 }
36
37 //显示队列
38 func (this *Queue) Show() {
39 if this.IsEmpty() {
40 fmt.Println("队列为空!")
41 }
42 temp := this.head
43 for i := 0; i < this.Size(); i++ {
44 fmt.Printf("array[%d]:%d\t",temp,this.array[temp])
45 temp = (temp + 1) % this.maxSize
46 }
47
48 }
49
50 //判断队列是否已满
51 func (this *Queue) IsFull() bool {
52 return (this.tail + 1) % this.maxSize == this.head
53 }
54
55 //判断队列是否为空
56 func (this *Queue) IsEmpty() bool {
57 return this.head == this.tail
58 }
59
60 //查询有多少个队列
61 func (this *Queue) Size() int {
62 return (this.tail + this.maxSize - this.head) % this.maxSize
63 }
64
65
66
67
68 func main(){
69
70 quque := &Queue {
71 maxSize : 5,
72 head : 0,
73 tail : 0,
74 }
75
76 var xz string
77 var number int
78 for {
79 fmt.Println()
80 fmt.Println("1.添加队列请输入add")
81 fmt.Println("2.获取队列请输入get")
82 fmt.Println("3.显示队列请输入show")
83 fmt.Println("4.输入exit退出")
84 fmt.Scanln(&xz)
85
86 switch xz {
87 case "add" :
88 fmt.Println("输入你要入列的数:")
89 fmt.Scanln(&number)
90 err := quque.Push(number)
91 if err != nil {
92 fmt.Println(err.Error())
93 } else {
94 fmt.Printf("加入队列成功!\n")
95 }
96 case "get" :
97 val, err := quque.Pop()
98 if err != nil {
99 fmt.Println(err.Error())
100 } else {
101 fmt.Printf("队列已取出:%d",val)
102 }
103
104 case "show" :
105 quque.Show()
106 fmt.Println()
107 case "exit" :
108 os.Exit(0)
109 }
110 }
111 }