顺序循环队列的基本操作 C语言

#include "stdio.h"
#include "stdlib.h"

#define N 10
#define MAXCSIZE 10  // 队列空间的初始分配量

typedef int ElemType; // 在实际应用中,根据需要定义所需的数据类型

typedef struct
{
    ElemType *base;     // 基地址
    int front;          // 队头指针
    int rear;           // 队尾指针
}cqueue;


// 初始化操作(创建一个空循环队列cq)
void initqueue(cqueue *cq)
{
    cq->base=(ElemType *)malloc(MAXCSIZE*sizeof(ElemType)); // 分配内存
    cq->front=cq->rear=0;                                   // 队头和队尾指针初始值都为0
}


// 求队列长操作(循环队列中数据元素的个数)
int getlen(cqueue *cq)
{
    return((cq->rear-cq->front+MAXCSIZE)%MAXCSIZE);
}


// 取队头元素操作(取出循环队列cq的队头元素值)
int getfront(cqueue *cq,ElemType *e)
{
    if(cq->front==cq->rear)
        return 0;                      // 队空,返回0
    *e=cq->base[cq->front];            // 取队头元素
    return 1;
}


// 入队列操作(在循环队列cq的队尾插入值为x的元素)
int enqueue(cqueue *cq,ElemType x)
{
    if((cq->rear+1)%MAXCSIZE==cq->front)
        return 0;                                  // 队满,返回0
    cq->base[cq->rear]=x;                          // 入队列
    cq->rear=(cq->rear+1)%MAXCSIZE;                // 修改队尾指针
    return 1;
}


// 出队列操作(将循环队列cq的队头元素删除)
int outqueue(cqueue *cq,ElemType *e)
{
    if(cq->front==cq->rear)
        return 0;                            // 队空,返回0
    *e=cq->base[cq->front];                  // 取队头元素
    cq->front=(cq->front+1)%MAXCSIZE;        // 修改队头指针
    return 1;
}


// 判队空操作(判断循环队列cq是否为空)
int emptyqueue(cqueue *cq)
{
    if(cq->front==cq->rear)
        return 1;
    else
        return 0;
}

// 输出操作(输出循环队列cq从队头到队尾的所有元素)
void list(cqueue *cq)
{   int i;
    i=cq->front;
    while(i!=cq->rear)
    {
        printf("%d ",cq->base[i]);
        i=(i+1)%MAXCSIZE;
    }
    printf("\n");
}

int main()
{
    cqueue Q;
    ElemType x;
    ElemType e;

    initqueue(&Q);

    printf("队列容量%d\n",MAXCSIZE);
    printf("入队列,输入%d个元素:\n",N);
    for(int i=1;i<=N;i++)
    {
        scanf("%d",&x);
        if(enqueue(&Q,x)==0)
        {
            printf("队满\n");
            break;
        }
 }
    list(&Q);

    printf("出队列:\n");
    outqueue(&Q,&e);
    printf("%d\n",e);
    printf("队列中剩余元素:");
    list(&Q);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值