package main
import (
"errors"
"fmt"
"os"
)
type
Queue
struct {
maxSize
int
array [
5]
int
//数组模拟队列
front
int
//指向队列首部
rear
int
//指向队列尾部
IsFull
bool
//是否已满,true为已满,false为未满
}
// 添加数据到队列
func (this *Queue)
AddQqueue(val
int) (err
error) {
//先判断是否队列已满
fmt.
Println(
"Queue length:",
len(this.array))
//如果尾指针和首指针相等且数组已满,则代表队列已满
if this.rear == this.front && this.IsFull {
return errors.
New(
"queue full!")
}
this.array[this.rear] = val
this.rear++
//尾指针加1
//如果尾指针等于数组长度,则尾指针归零
if this.rear == this.maxSize {
this.rear =
0
}
//如果首指针和尾指针相等,则代表已满
if this.rear == this.front {
this.IsFull =
true
}
fmt.
Printf(
"value =
%d
,this.rear =
%d
,this.front =
%d
\n
", val, this.rear, this.front)
return
}
// 从队列中取出数据
func (this *Queue)
GetQueue() (val
int, err
error) {
//先判断队列是否为空
if this.rear == this.front && !this.IsFull {
return -
1, errors.
New(
"queue empty")
}
val = this.array[this.front]
this.front++
if this.front == this.maxSize {
this.front =
0
}
this.IsFull =
false
fmt.
Printf(
"value =
%d
,this.rear =
%d
,this.front =
%d
\n
", val, this.rear, this.front)
return val, err
}
// 显示队列,找到队首,然后遍历到队尾
func (this *Queue)
ShowQueue() {
fmt.
Println(
"队列当前的情况是:")
fmt.
Printf(
"this.rear =
%d
,this.front =
%d
\n
", this.rear, this.front)
//分三种情况输出队列数据,1.rear > front 2.rear < front 3. rear = front
if this.rear > this.front {
for
i := this.front; i < this.rear; i++ {
fmt.
Printf(
"array[
%d
] =
%d
\t\n
", i, this.array[i])
}
}
else
if this.rear < this.front {
for
i := this.front; i < this.maxSize; i++ {
fmt.
Printf(
"array[
%d
] =
%d
\t\n
", i, this.array[i])
}
for
i :=
0; i < this.rear; i++ {
fmt.
Printf(
"array[
%d
] =
%d
\t\n
", i, this.array[i])
}
}
else
if this.rear == this.front && this.IsFull {
for
i :=
0; i < this.maxSize; i++ {
fmt.
Printf(
"array[
%d
] =
%d
\t\n
", i, this.array[i])
}
}
fmt.
Println()
}
func
min(a, b
int)
int {
if a < b {
return a
}
return b
}
func
max(a, b
int)
int {
if a > b {
return a
}
return b
}
// 编写一个主函数
func
main() {
//先创建一个队列
queue := &Queue{
maxSize:
5,
front:
0,
rear:
0,
IsFull:
false,
}
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.
AddQqueue(val)
if err ==
nil {
fmt.
Println(
"加入队列成功")
}
else {
fmt.
Println(err.
Error())
}
case
"get":
val,
err := queue.
GetQueue()
if err !=
nil {
fmt.
Println(err.
Error())
}
else {
fmt.
Println(
"从队列中取出了一个数:", val)
}
case
"show":
queue.
ShowQueue()
case
"exit":
os.
Exit(
0)
}
}
}