循環隊列是數據結構中的經典結構,通過首尾相連的方式解決假溢出問題。本文提供完整的 C 語言實現代碼,包含頭文件定義、基本操作函數、測試主程序及運行結果演示。
sqqueue.h定義隊列存儲結構、常量、類型別名及所有操作函數原型:
base、頭指針 front、尾指針 rearMAXQSIZE = 500int,支持通過宏定義自定義// 循環隊列存儲結構
#define MAXQSIZE 500
typedef struct {
ElemType *base;
int front;
int rear;
} SqQueue;
// 入隊操作 - 核心邏輯
Status EnQueue(SqQueue &Q, ElemType e) {
if ((Q.rear + 1) % MAXQSIZE == Q.front) // 隊滿判斷
return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE; // 尾指針循環遞增
return OK;
}
// 出隊操作 - 核心邏輯
Status DeQueue(SqQueue &Q, ElemType &e) {
if (Q.front == Q.rear) // 隊空判斷
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE; // 頭指針循環遞增
return OK;
}
演示隊列的基本操作流程:初始化 → 入隊數據 → 查看長度 → 取隊頭 → 出隊 → 再次查看隊頭:
int main() {
SqQueue q;
int x;
InitQueue(q);
printf("數據元素進隊列,以0結束");
scanf("%d", &x);
while (x != 0) {
EnQueue(q, x);
scanf("%d", &x);
}
printf("\n隊列元素個數: %d", QueueLength(q));
if (!QueueEmpty(q) && GetHead(q, x) == OK)
printf("\n頭元素是: %d", x);
if (DeQueue(q, x) == OK)
printf("\n出隊列元素: %d", x);
if (!QueueEmpty(q) && GetHead(q, x) == OK)
printf("\n此時隊頭是: %d", x);
return 0;
}

(index + 1) % MAXQSIZE 實現指針循環front == rear 為空;(rear + 1) % MAXQSIZE == front 為滿(犧牲一個存儲單元)QueueView() 函數可視化隊列狀態本文出自 “趙玉強的博客”,轉載請保留出處:原文鏈接