#define MAXSIZE 50
typedef char ElemType;
typedef struct {
ElemType data[MAXSIZE];
int front, rear;
int tag; // 0: 空, 1: 滿
} SqQueue;
void InitQueue(SqQueue *Q) {
Q->front = Q->rear = 0;
Q->tag = 0;
}
bool EnQueue(SqQueue *Q, ElemType x) {
if (Q->front == Q->rear && Q->tag == 1) return false; // 滿
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAXSIZE;
if (Q->front == Q->rear) Q->tag = 1; // 變滿
return true;
}
bool DeQueue(SqQueue *Q, ElemType *x) {
if (Q->front == Q->rear && Q->tag == 0) return false; // 空
*x = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
if (Q->front == Q->rear) Q->tag = 0; // 變空
return true;
}
while ((c = getchar()) != '\n' ); // 此處多餘分號導致循環體為空!
EnQueue(&Q, c); // 只執行一次,且 c 已為 '\n'
分號導致 while 循環無執行體,直接跳過輸入處理,後續入隊操作使用的是換行符。去掉分號即可修復。
傳統循環隊列犧牲一個存儲單元區分滿/空((rear+1)%MAX == front 為滿),引入 tag 後可利用全部 MAXSIZE 個空間,邏輯更直觀。