C语言循环队列(数组实现)

#include <stdio.h>
#include <stdlib.h>

typedef struct queue_arr
{
    int * data;
    int front;
    int rear;
    int count;
} que;

//初始化队列
que * InitQueue()
{
    que * q = (que *)malloc(sizeof(que));
    q->front = 0;
    q->rear = 0;
    q->count = 0;//可用于判断队空、队满
    return q;
}

//判断队满
int FullQueue(que * q)
{
    //设置队列长度为10
    if((q->rear+1)%10 == q->front)
        return 0;
    return 1;
}

//入队函数
int EnQueue(que * q, int data)
{
    if(FullQueue(q) == 0)
    {
        return 1;
    }
    else
    {
        q->data[q->rear] = data;
        q->rear = (q->rear+1)%10;
        q->count++;
        return 0;
    }
}

//出队函数
que * DelQueue(que * q, int data)
{
    que * del = q;
    int tmp = del->front,n = del->count;
    if(q->count == 0)//判断队空
        return q;

    while(n)
    {
        n--;
        if(del->data[tmp] == data)
          {
              del->front = (tmp+1)%10;
              del->count = n;
              return del;
          }
        tmp = (tmp+1)%10;

    }

    return q;
}

//遍历队列

void Display(que * q)
{
    int i =q->front;
    while(i != q->rear)
    {
        printf("%d ",q->data[i]);
        i = (i+1)%10;
    }
    if(q->count == 0)
        printf("队列为空!");
    printf("\n");
}
//测试代码
int main()
{
    que * q;
    int i=10;
    q = InitQueue();
    printf("开始入队\n");
    while(i--)
    {
            if(EnQueue(q,i) == 1)
            printf("队满,不能入队!\n");
            else
            {
                printf("数字 %d 入队后,队列成员为:",i);
                Display(q);
            }
    }
    i=10;
    printf("开始出队\n");
    while(i--)
    {
        DelQueue(q,i);
        printf("数字 %d 出队后,队列成员为:",i);
        Display(q);
    }
}

 

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值