#include "bits/stdc++.h"
using namespace std;
#define OK 0
#define ERROR -1
#define MAXQSIZE 100
typedef struct {
int *base;
int front;
int rear;
} SqQueue;
int InitQueue(SqQueue &Q) {
Q.base = new int[MAXQSIZE];
if (Q.base == NULL) {
cerr << "队列初始化失败" << endl;
return ERROR;
} else {
Q.front = Q.rear = 0;
cout << "队列初始化成功" << endl;
return OK;
}
}
int QueueLength(SqQueue Q) {
return ((Q.rear - Q.front + MAXQSIZE) % MAXQSIZE);
}
int EnQueue(SqQueue &Q, int e) {
if ((Q.rear + 1) % MAXQSIZE == Q.front) {
cerr << "循环队列已经满了,入队失败" << endl;
return ERROR;
} else {
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
cout << "入队成功" << endl;
return OK;
}
}
int DeQueue(SqQueue &Q) {
if (Q.front == Q.rear) {
cerr << "队空,出队失败" << endl;
return ERROR;
} else {
Q.front = (Q.front + 1) % MAXQSIZE;
cout << "出队成功" << endl;
return OK;
}
}
int GetHead(SqQueue Q) {
if (Q.front != Q.rear) {
return Q.base[Q.front];
}
}
int main() {
SqQueue Q;
InitQueue(Q);
int choice;
do {
cout << "1.入队" << endl;
cout << "2.出队" << endl;
cout << "3.取队头元素" << endl;
cout << "4.队列长度" << endl;
cout << "************************" << endl;
cout << "请输入您的选择:" << endl;
cin >> choice;
switch (choice) {
case 1: {
int e;
cout << "请输入您要入队的元素:" << endl;
cin >> e;
EnQueue(Q, e);
break;
}
case 2: {
DeQueue(Q);
break;
}
case 3: {
int res;
res = GetHead(Q);
cout << "队头元素为:" << res << endl;
break;
}
case 4: {
int length = QueueLength(Q);
cout << "队列的长度为:" << length << endl;
break;
}
default: {
exit(ERROR);
}
}
} while (1);
return 0;
}