循环队列的表示和实现

来源:互联网 发布:软件卡住关不掉 编辑:程序博客网 时间:2024/05/24 02:40

//库函数头文件包含#include <stdio.h>#include <stdlib.h>#include <malloc.h>//函数状态码的定义#define TRUE        1#define FALSE       0#define OK          1#define ERROR       0#define OVERFLOW   -2#define MAXQSIZE    100typedef int Status;typedef int QElemType;//-----循环队列————队列的顺序存储结构-----------typedef struct SqQueue{    QElemType *base;    int Front;    int Rear;}SqQueue;//----------循环队列的基本操作的实现-----------//构造一个空队列QStatus InitQueue(SqQueue &Q){    Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));    if(!Q.base)        exit(OVERFLOW);         //储存分配失败    Q.Front = Q.Rear = 0;    return OK;}//销毁队列Status DestroyQueue(SqQueue &Q){    free(Q.base);    Q.Front = Q.Rear = 0;    return OK;}//清空队列Status ClearQueue(SqQueue &Q){    Q.Front = Q.Rear = 0;       //此处不一定非得等于0,等于其它的也可以,只要保证Q.Front = Q.Rear并且不超过最大容量就行    return OK;}//返回队列的长度int QueueLength(SqQueue Q){    return (Q.Rear - Q.Front + MAXQSIZE) % MAXQSIZE;}//返回队头元素Status GetHead(SqQueue Q, QElemType &e){    if(Q.Rear == Q.Front)        return ERROR;    e = Q.base[Q.Front];    return OK;}//判断队列是否为空Status Is_QueueEmpty(SqQueue Q){    if(Q.Rear == Q.Front)        return TRUE;    return FALSE;}//入队Status EnQueue(SqQueue &Q, QElemType e){    if((Q.Rear + 1) % MAXQSIZE == Q.Front)      //如果队列已经满了,就不再添加新元素        return ERROR;    Q.base[Q.Rear] = e;    Q.Rear = (Q.Rear + 1) % MAXQSIZE;           //加就可能会越界,因此要取余数    return OK;}//出队Status DeQueue(SqQueue &Q, QElemType &e){    if(Q.Rear == Q.Front)        return ERROR;    e = Q.base[Q.Front];    Q.Front = (Q.Front + 1) % MAXQSIZE;    return OK;}//visit()函数Status Print(QElemType e){    printf("%d ", e);    return OK;}//队列的遍历Status QueueTraverse(SqQueue Q, Status (*visit)(QElemType)){    for(int i = Q.Front; i != Q.Rear; i = (i + 1) % MAXQSIZE){        if(!visit(Q.base[i]))            return ERROR;    }    return OK;}//主函数int main(){    SqQueue Q;    QElemType a;    InitQueue(Q);    printf("输入5个数:\n");    for(int i = 0; i < 5; ++i){        scanf("%d", &a);        EnQueue(Q, a);    }    printf("遍历队列:\n");    QueueTraverse(Q, Print);    DeQueue(Q, a);    printf("\n执行一次出队操作的结果:\n");    QueueTraverse(Q, Print);    printf("\n获得队列长度操作的结果:\n%d", QueueLength(Q));    GetHead(Q, a);    printf("\n获得队头元素操作的结果:\n%d", a);    printf("\n判断队列是否为空:\n");    if(Is_QueueEmpty(Q))        printf("YES");    else        printf("NO");    printf("\n执行清空队列操作后队列是否为空:\n");    ClearQueue(Q);    if(Is_QueueEmpty(Q))        printf("YES");    else        printf("NO");    DestroyQueue(Q);    return 0;}

下面是对代码的简单测试结果: