7-3 环形队列基本运算 (10 分)

编写一个程序实现顺序循环队列(假设队列中元素类型为char)的各种基本运算,并在此基础上设计一个主程序完成如下功能:
(1)初始化队列q;
(2)判断队列q是否为空;
(3)依次进队列元素;
(4)出队一个元素,并输出该元素;
(5)输出队列q的元素个数;
(6)依次进队列元素;
(7)输出队列q的元素个数;
(8)输出出队序列;
(9)释放队列。

输入格式:

输入两行数据,第一行是进队字符数据的个数,第二行是具体入队的字符数据。

输出格式:

按照程序要求输出。

输入样例:

3
a b c 
3
d e f

输出样例:

yes
a
2
5
b c d e f
#include<stdio.h>
#include<malloc.h>
#define MaxSize 10
typedef char ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int front,rear;     //队首和队尾指针
} SqQueue;
void InitQueue(SqQueue *&q) //初始化队列
{   q=(SqQueue *)malloc (sizeof(SqQueue));
    q->front=q->rear=0;
}
void DestroyQueue(SqQueue *&q)  //销毁队列
{
    free(q);
}
bool QueueEmpty(SqQueue *q) //判断队列空
{
    return(q->front==q->rear);
}
bool enQueue(SqQueue *&q,ElemType e)    //进队
{
    if ((q->rear+1)%MaxSize==q->front)  //队满上溢出
        return false;
    q->rear=(q->rear+1)%MaxSize;
    q->data[q->rear]=e;
    return true;
}
bool deQueue(SqQueue *&q,ElemType &e)   //出队
{
    if (q->front==q->rear)      //队空下溢出
        return false;
    q->front=(q->front+1)%MaxSize;
    e=q->data[q->front];
    return true;
}
int length(SqQueue *&q){
    if(q->rear>q->front)
        return q->rear-q->front;
    else
        return q->front-q->rear;
}
int main()
{
    ElemType e;
    SqQueue *q;
    InitQueue(q);
    int n;
    scanf("%d",&n);
    getchar();
    int i;
    if(QueueEmpty(q)) printf("yes\n");
    else printf("no\n");
    for(i=0;i<n;i++){
        scanf("%c ",&e);
        enQueue(q,e);
    }
    deQueue(q,e);
    printf("%c\n",e);//出队元素
    printf("%d\n",length(q));//队列元素
    scanf("%d",&n);//进队个数
    getchar();
    for(i=0;i<n;i++){
        scanf("%c ",&e);//进队元素
        enQueue(q,e);
    }
    printf("%d\n",length(q));//队列元素个数
    int k=0;
    while (!QueueEmpty(q))
    {   deQueue(q,e);
        if(k==0)k=1;          //输出元素
        else
            printf(" ");
        printf("%c",e);
    }
    printf("\n");
    DestroyQueue(q);//释放
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值