代码如下:
#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("正在创建循环队列... 创建成功! "); printf("请输入存入循环队列的数据:"); ElemType e; while ((e = getchar())!=' ') { if (e!=' ') { EnQueue(&q,e); } } printf("正在打印循环队列... 当前循环队列为:"); for (size_t i = 0; i < q.rear; i++) { printf("%c",q.base[q.front+i]); } putchar(' '); printf("请输入要从队头出队列几个元素:"); int c; scanf("%d",&c); while (c) { DeQueue(&q , &e); printf("%c已出循环队列! ",e); c--; } printf("正在打印循环队列... 当前循环队列为:"); for (size_t i = 0; i < q.rear; i++) { printf("%c",q.base[q.front+i]); } putchar(' '); return 0; }
运行结果: