#include<iostream>
#include<stdlib.h>
using namespace std;
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef int Status;
typedef int QElemType;
#define MAXSIZE 100 // 最大长度
/*------------静态分配------------*/
//typedef struct {
// QElemType elem[MAXSIZE];
// QElemType* rear; // 队尾指针
// QElemType* front; // 队头指针
// int length; // 长度
//}SqQueue;
/*------------动态分配------------*/
typedef struct {
QElemType* elem; // 动态分配存储空间初始化
int rear; // 尾指针
int front; // 头指针
}SqQueue;
// 构造空队列
Status InitSqQueue(SqQueue& Q) {
Q.elem = new QElemType[MAXSIZE];
if (!Q.elem) exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
// 队列长度
int QueueLength(SqQueue Q) {
return(Q.rear - Q.front) % MAXSIZE;
}
// 判断队列是否为空
bool IsSqQueueEmpty(SqQueue Q) {
return Q.rear == Q.front;
}
// 判断队列是否满
bool IsSqQueueFull(SqQueue Q) {
return (Q.rear + 1) % MAXSIZE == Q.front;
}
// 入队
Status PushSqQueue(SqQueue& Q, QElemType e) {
if (IsSqQueueFull(Q)) return ERROR;
Q.elem[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
return OK;
}
// 出队
Status PopSqQueue(SqQueue& Q, QElemType &e) {
if (IsSqQueueEmpty(Q)) return ERROR;
e = Q.elem[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return OK;
}
// 创建队列
void CreatSqQueue(SqQueue& Q, int m) {
QElemType e;
for (int i = 1; i <= m; i++) {
cout << "请输入第" << i << "个元素的值: ";
cin >> e;
PushSqQueue(Q, e);
}
}
// 输出队列
void OutPut(SqQueue Q) {
int i;
i = Q.front;
while (i != Q.rear) {
cout << Q.elem[i] << " ";
i = (i + 1) % MAXSIZE;
}
cout << endl;
}
int main()
{
// 测试代码
SqQueue Q;
QElemType e;
int m;
InitSqQueue(Q);
cout << "请输入队列的长度: ";
cin >> m;
CreatSqQueue(Q, m);
OutPut(Q);
cout << "队列的长度为: " << QueueLength(Q) << endl;
cout << "请输入入队元素: ";
cin >> e;
PushSqQueue(Q, e);
cout << "队列元素为: ";
OutPut(Q);
cout << "队列的长度为: " << QueueLength(Q) << endl;
PopSqQueue(Q, e);
cout << "出队元素为: " << e << endl;
cout << "队列元素为: ";
OutPut(Q);
cout << "队列的长度为: " << QueueLength(Q) << endl;
return 0;
}
评论