循环队列的实现,插入,删除,打印,求长度

时间:2023-01-06 21:42:29
#include<iostream>
#define MAXSIZE 10
#define OK 1
#define ERROR 0
using namespace std;
typedef intQElemType;

//定义循环队列结构
typedef struct
{
QElemType *base;//初始化的动态分配存储空间
int front;//头指针,若队列不为空,指向队头元素
int rear;//尾指针,若队列不为空,指向队尾元素的下一个位置
//注:front,rear本身不是指针,是两个下标,类似数组的下标
}SqQueue;

//创建循环队列
int InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXSIZE *sizeof(QElemType));
if (!Q.base) return ERROR;
Q.front = Q.rear = 0;//初始时,头尾指针均为0;
return OK;
}

//返回循环队列数据长度
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}

//队头插入元素
void EnQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAXSIZE == Q.front) cout << "队列已满!" << endl;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;//%的作用:当Q.rear+1达到MAXSIZE时,Q.rear从0开始
}

//删除队尾元素
void DeQueue(SqQueue &Q)
{
if (Q.rear == Q.front) cout << "循环队列为空,删除失败!" << endl;
Q.front = (Q.front + 1) % MAXSIZE;
cout <<"循环队列队头元素"<<Q.base[Q.front-1]<<"删除成功!" << endl;
}

//打印循环队列
void PrintQueue(SqQueue &Q)
{
int i,length;
length = QueueLength(Q);
cout << "循环队列元素:" << endl;
for (i = 0; i < length; i++)
{
cout << Q.base[(Q.front + i) % MAXSIZE] << endl;
}
}
void main()
{
SqQueue Q;
QElemType length;
int i = 0;
cout << endl << endl << "循环队列的实现";
cout << endl << "==============";
if (InitQueue(Q))
cout << endl << endl << "Success ! The SqQueue has been initilized !" << endl;
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
EnQueue(Q, 6);
PrintQueue(Q);

DeQueue(Q);
PrintQueue(Q);
system("pause");
}