C++实现循环队列

本文采用“队列头指针在队列尾指针的下一个位置上表示队列满”(即少用一个元素空间)的方式来书写代码
本文的思路主要参考严蔚敏老师编写的《数据结构》

//循环队列
#include <iostream>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXQSIZE 100
#define QElemType int
typedef int Status;
using namespace std;
typedef struct
{
    QElemType *base; //初始化的动态分配存储空间
    int thefront;
    int therear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{//初始化一个空的循环队列
    Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
    if(!Q.base)
        exit(OVERFLOW);
    else
    {
        Q.thefront=Q.therear=0;
        return OK;
    }
}
int QueueLength(SqQueue Q)
{
    return(Q.therear-Q.thefront+MAXQSIZE)%MAXQSIZE;
}
//Status EnQueue(SqQueue &Q,QElemType e)
//{//插入新的元素e为Q的新的队尾元素
//    if(Q.thefront==Q.therear=0)
//        Q.thefront=e;
//    else
//    {
//        Q.therear=e;
//        Q.therear+=1;
//    }
//}
Status EnQueue(SqQueue &Q,QElemType e)
{//插入新的元素e为Q的新的队尾元素
    if((Q.therear+1)%MAXQSIZE==Q.thefront)//若队列满
        return ERROR;
    Q.base[Q.therear]=e;
    Q.therear=(Q.therear+1)%MAXQSIZE;//将队尾的值加一
    return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)
{//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK,否则返回error
    if(Q.thefront==Q.therear)
        return ERROR;
        e=Q.base[Q.thefront];
        Q.thefront=(Q.thefront+1)%MAXQSIZE;
        return OK;
}
void PrintQueue(SqQueue q)
{//若循环队列不为空,则输出循环队列中的元素,否则输出null
    if(q.thefront==q.therear)
        cout<<"null"<<endl;
    else if(q.thefront<q.therear)
    {
        int i;
        for(i=q.thefront;i<q.therear;i++)
        {
            cout<<q.base[i]<<" ";
        }
        cout<<endl;
    }
    else if(q.thefront>q.therear)
    {
        int i;
        for(i=q.thefront;i<MAXQSIZE;i++)
        {
             cout<<q.base[i]<<" ";
        }
        for(i=0;i<q.therear;i++)
        {
            cout<<q.base[i]<<" ";
        }
        cout<<endl;
    }
}
int main()
{
    SqQueue a;
    InitQueue(a);
    EnQueue(a,1);
    EnQueue(a,2);
    EnQueue(a,3);
    PrintQueue(a);
    QElemType b;
    DeQueue(a,b);
    PrintQueue(a);
}

运行结果:
在这里插入图片描述
若以上代码有任何错误或需要改进的地方欢迎在评论区指出并讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值