首页 > 技术文章 > 数据结构C语言实现----循环队列

jerryleesir 2020-07-19 16:45 原文

代码如下:

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

typedef char ElemType;
#define MAXQUEUE 100

typedef struct
{
    ElemType *base;
    int front;
    int rear;
}cycleQueue;

/////////////////////////////////
//创建一个循环队列
void initqueue(cycleQueue *q)
{
    q->base = (ElemType*)malloc(sizeof(cycleQueue) * MAXQUEUE);//为循环队列申请连续空间
    if (!q->base)
    {
        exit(0);
    }
    q->front = q->rear = 0;//初始换队首队尾位置为0
}

/////////////////////////////////
//入循环队列
void EnQueue(cycleQueue *q , ElemType e)
{
    if ((q->rear+1) % MAXQUEUE== q->front)
    {
        return;
    }
    q->base[q->rear] = e;
    q->rear = (q->rear+1)%MAXQUEUE;
}

///////////////////////////////////
//出循环列表
void DeQueue(cycleQueue *q , ElemType *e)
{
    if (q->rear == q->front)
    {
        return;
    }
    *e = q->base[q->front];
    q->front = (q->front+1)%MAXQUEUE;
}

int main()
{
    cycleQueue q;
    initqueue(&q);
    printf("正在创建循环队列...\n创建成功!\n");

    printf("请输入存入循环队列的数据:");
    ElemType e;
    while ((e = getchar())!='\n')
    {
        if (e!='\n')
        {
            EnQueue(&q,e);
        }
    }
    
    printf("正在打印循环队列...\n当前循环队列为:");
    for (size_t i = 0; i < q.rear; i++)
    {
        printf("%c",q.base[q.front+i]);
    }
    putchar('\n');

    printf("请输入要从队头出队列几个元素:");
    int c;
    scanf("%d",&c);
    while (c)
    {
        DeQueue(&q , &e);
        printf("%c已出循环队列!\n",e);
        c--;
    }

    printf("正在打印循环队列...\n当前循环队列为:");
    for (size_t i = 0; i < q.rear; i++)
    {
        printf("%c",q.base[q.front+i]);
    }
    putchar('\n');
    return 0;
}

  

运行结果:

 

推荐阅读