循环队列的实现

来源:互联网 发布:亚洲蹲 知乎 编辑:程序博客网 时间:2024/06/18 05:43
#include<cstdio>#include<cstdlib>#include<iostream>using namespace std;typedef int QElementType;typedef int status;#define _ERROR 0#define _OK 1#define MAXQSIZE 10//队列的数据抽象typedef struct{QElementType *base;//这里相当于存储数据的数组,只不过我这里是动态分配存储空间,一个连续的存储空间int front;//队列头指针int rear;//队列尾指针}SqQueue;//队列初始化函数status InitQueue(SqQueue &Q){Q.base = (QElementType*)malloc(MAXQSIZE * sizeof(QElementType));//分配了一个连续的整型地址,由base指针指向其首地址if (Q.base == NULL)return _ERROR;Q.front = Q.rear = 0;return _OK;}//判断队列是否为空bool IsEmpty(SqQueue Q){return Q.front == Q.rear;}//判断队列是否已满,这里我们牺牲一个空间,为什么?你懂的bool IsFull(SqQueue Q){return ((Q.rear + 1) % MAXQSIZE) == Q.front;}//获取队列长度int QueueLength(SqQueue Q){return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;}//入队列status InQueue(SqQueue &Q, QElementType e){//判断队列是否已满if (IsFull(Q))return _ERROR;Q.base[Q.rear] = e;Q.rear = (Q.rear + 1) % MAXQSIZE;return _OK;}//出队列status OutQueue(SqQueue &Q, QElementType &e)//这里是引用,不是取地址{//判断队列是否为空if (IsEmpty(Q))return _ERROR;e = Q.base[Q.front];Q.front = (Q.front + 1) % MAXQSIZE;return _OK;}//打印队列中的元素void PrintQueue(SqQueue Q){for (int i = Q.front; i%MAXQSIZE < Q.rear; i++){printf("%d\n", Q.base[i]);}}//取队头元素bool GetFront(SqQueue &Q, QElementType &e){if (IsEmpty(Q))return _ERROR;e = Q.base[Q.front];return _OK;}int main(){//初始化队列SqQueue Q;InitQueue(Q);printf("入队列测试:\n");//入队列测试InQueue(Q, 1);InQueue(Q, 2);InQueue(Q, 3);InQueue(Q, 4);InQueue(Q, 5);InQueue(Q, 6);InQueue(Q, 7);InQueue(Q, 8);InQueue(Q, 9);PrintQueue(Q);printf("取队头元素:\n");//取队头元素测试QElementType e1;GetFront(Q, e1);printf("%d\n", e1);printf("溢出测试:\n");//溢出测试InQueue(Q, 10);PrintQueue(Q);printf("出队列测试:\n");//出队列测试QElementType e;OutQueue(Q, e);printf("%d\n", e);OutQueue(Q, e);printf("%d\n", e);printf("长度测试:\n");//长度测试printf("%d\n", QueueLength(Q));system("pause");return 0;}

0 0
原创粉丝点击