实验目标:

(1)初始化长度为MAXQSIZE的空队列

(2)新元素e入队列,成功返回true,失败返回false

(3)出队列,即删除队首元素,并用e返回出元素值,成功返回true,失败返回false

(4)读队首元素,用e返回队首元素,不出队 ,成功返回true,失败返回false

(5)遍历队列

(6)销毁队列


实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <bits/stdc++.h>
using namespace std;

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

#define MAXSIZE 100

typedef int Status;
typedef int QElemType;

typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;

Status InitQueue(SqQueue &Q)//初始化队列
{
Q.base=(QElemType*)malloc(MAXSIZE *sizeof(QElemType));
if(!Q.base)exit(OVERFLOW);
Q.front=Q.rear=0;
return OK;
}

Status EnQueue(SqQueue &Q,QElemType e)//入队列
{
if((Q.rear+1) % MAXSIZE==Q.front) return ERROR;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1) % MAXSIZE;
return OK;
}

Status DeQueue(SqQueue &Q,QElemType &e)//将队列首元素删除并返回其值
{
if(Q.front==Q.rear) return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1) % MAXSIZE;
return OK;
}

Status GetHead(SqQueue &Q)//读出队首元素,不出队
{
if(Q.front==Q.rear) return FALSE;
cout<<Q.base[Q.front]<<endl;
return OK;
}

Status Traverse(SqQueue &Q)//遍历队列
{
if(Q.front==Q.rear) return FALSE;

int i=Q.front;
while(i!=Q.rear){
cout<<Q.base[i]<<" ";
i++;
i=i%MAXSIZE;
}
return OK;
}

Status Destroy(SqQueue &Q)
{
if(Q.front==Q.rear) return FALSE;

if(Q.base) free(Q.base);
Q.base=NULL;
Q.front=Q.rear=0;
return OK;
}

int main()
{
SqQueue Q;
int e;

while(1){
cout<<endl;
cout<<"**1,初始化队列"<<endl;
cout<<"**2,将元素e入列"<<endl;
cout<<"**3,出队列,用e返回出队列元素"<<endl;
cout<<"**4,返回列首元素"<<endl;
cout<<"**5,遍历队列"<<endl;
cout<<"**6,销毁队列"<<endl;
cout<<"**0,退出系统"<<endl<<endl;

int choice;
cout<<"请输入要进行的操作:";
cin>>choice;
cout<<endl;

switch(choice){
case 1:InitQueue(Q);break;
case 2:{
int n;
cout<<"请输入本次入队的元素个数:";
cin>>n;

cout<<endl<<"请输入要插入的元素:";
for(int i=1;i<=n;i++){
cin>>e;
EnQueue(Q,e);
}
cout<<"入栈成功!"<<endl;
break;
}
case 3:{
DeQueue(Q,e);
cout<<"出队成功!"<<endl;
break;
}
case 4:GetHead(Q);break;
case 5:Traverse(Q);break;
case 6:Destroy(Q);break;
case 0:exit(0);
}
}

system("pause");
return 0;
}