循环队列的实现

同样老师不让直接用queue这个容器,所以自己实现咯!
循环队列很厉害呢!!

#include<cstdio>
#include<cstdlib>
using namespace std;
const int MAXSIZE = 100;
typedef struct{
    int *base;
    int front;
    int rear; 
}SqQueue;
/*初始化队列*/
bool Init(SqQueue &q)
{
    q.base = (int *)malloc(MAXSIZE*sizeof(int));
    if(!q.base) return 0;
    q.front = q.rear = 0;
    return 1;
}
/*求队列长度*/
int QueueLength(SqQueue &q)
{
    return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
/*判断队列是否为空*/
bool IsEmpty(SqQueue q)
{
    return q.front == q.rear;
} 
/*取队头元素*/
bool GetFront(SqQueue &q, int &e)
{
    if(IsEmpty(q)) return 0;
    e = q.base[q.front];
    return 1;
}
/*入队*/
bool EnQueue(SqQueue &q, int e)
{
    if((q.rear+1)%MAXSIZE == q.front) return 0;//队满
    q.base[q.rear] = e;
    q.rear = (q.rear+1) % MAXSIZE;
    return 1; 
}
/*出队*/
bool DeQueue(SqQueue &q)
{
    if(q.front == q.rear) return 0;//队空
    q.front = (q.front+1) % MAXSIZE; 
    return 1;
} 
/*打印队列,并清空队列*/
void PrintQueue(SqQueue &q)
{
    printf("此时队列为:"); 
    while(!IsEmpty(q))
    {
        int e;
        GetFront(q, e);
        printf("%d ",e);
        DeQueue(q);
    }
}
int main()
{
    SqQueue q;
    Init(q);
    while(1)
    {
        printf("\n");
        printf("1.入队  2.出队  3.输出队首元素  4.查询队列长度  5.退出 :");
        int choose;
        scanf("%d",&choose);
        if(choose == 5) break;
        int e;
        switch(choose)
        {
            case 1:
                printf("输入要入队的元素:");
                scanf("%d",&e);
                if(!EnQueue(q, e)) printf("队已满\n");
                break;
            case 2:
                if(!DeQueue(q))
                printf("队已空\n");
                break;          
            case 3:
                if(GetFront(q, e)) printf("队首元素为 %d\n",e);
                else printf("队已空\n");
                break;  
            case 4:
                printf("队列长度为 %d\n",QueueLength(q));
                break;  
        }
    }
    PrintQueue(q);
    return 0;
}

运行图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值