C 迴圈佇列的基本操作
阿新 • • 發佈:2019-01-26
程式碼片
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 5
typedef struct node* SeQuence;
struct node {
char data[MaxSize];
int Front, Rear; //Front隊頭,出隊用,Rear隊尾,入隊用
};
//初始化
void InitQuence(SeQuence *L) {
(*L) = (SeQuence)malloc(sizeof(struct node));
(*L)->Front = 0;
(*L)->Rear = 0 ;
}
//入隊
void AadQuence(SeQuence L, char x) {
if ((L->Rear + 1) % MaxSize == L->Front) { //Front和Rear相遇佇列滿
printf("滿佇列");
}
else {
L->Rear = (L->Rear + 1) % MaxSize; //隊尾加一
L->data[L->Rear] = x;
}
}
//出隊
void DeQuence(SeQuence L, char *x) {
if (L->Front ==L->Rear) { //相等說明空佇列
printf("空佇列");
}
else {
L->Front = (L->Front + 1) % MaxSize; //隊頭加一
*x = L->data[L->Front];
}
}
void PrintQuence(SeQuence L) {
int i;
i = (L->Front + 1) % MaxSize; //隊頭加一開始遍歷
while (i != L->Rear) {
printf ("%c", L->data[i]);
i = (i + 1) % MaxSize;
}
printf("%c", L->data[i]); //隊尾
printf("\n");
}
int main() {
SeQuence q;
char* y;
char x;
y = &x;
InitQuence(&q);
printf("輸入資料:\n");
scanf("%c", &x);
while (x != '\n') {
AadQuence(q, x);
scanf("%c", &x);
}
PrintQuence(q);
DeQuence(q, y);
printf("出隊資料是:%c\n",*y);
printf("剩餘:\n");
PrintQuence(q);
}