資料結構C語言實現----迴圈佇列
阿新 • • 發佈:2020-07-19
程式碼如下:
#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; }
執行結果: