隊列是先進先出(FIFO)的線性結構。用數組實現時,為避免數據搬移,採用循環數組(環形緩衝區)配合 `Front`、`Rear`、`Size` 三個索引/計數器。本文提供完整、可編譯運行的 C 實現。
#define MinQueueSize 5
typedef struct QueueRecord *Queue;
struct QueueRecord {
int Capacity; // 數組容量
int Front; // 隊頭索引
int Rear; // 隊尾索引(指向最後一個元素)
int Size; // 當前元素個數
int *Array; // 動態分配的數組
};
Queue CreateQueue(int capacity) {
if (capacity < MinQueueSize) {
fprintf(stderr, "Queue size too small\\n");
exit(1);
}
Queue Q = malloc(sizeof(struct QueueRecord));
Q->Array = malloc(sizeof(int) * capacity);
if (!Q || !Q->Array) { fprintf(stderr, "Out of space\\n"); exit(1); }
Q->Capacity = capacity;
Q->Size = 0;
Q->Front = 0;
Q->Rear = -1; // 空隊列約定
return Q;
}
int IsEmpty(Queue Q) { return Q->Size == 0; }
int IsFull(Queue Q) { return Q->Size == Q->Capacity; }
void Enqueue(Queue Q, int X) {
if (IsFull(Q)) { fprintf(stderr, "Full queue\\n"); return; }
Q->Rear = (Q->Rear + 1) % Q->Capacity; // 環形遞增
Q->Array[Q->Rear] = X;
Q->Size++;
}
void Dequeue(Queue Q) {
if (IsEmpty(Q)) { fprintf(stderr, "Empty queue\\n"); return; }
Q->Front = (Q->Front + 1) % Q->Capacity;
Q->Size--;
}
int Front(Queue Q) {
if (IsEmpty(Q)) { fprintf(stderr, "Empty queue\\n"); exit(1); }
return Q->Array[Q->Front];
}
void ShowQueue(Queue Q) {
if (IsEmpty(Q)) { printf("Queue empty\\n"); return; }
printf("Front=%d Rear=%d Size=%d: ", Q->Front, Q->Rear, Q->Size);
for (int i = 0, idx = Q->Front; i < Q->Size; i++, idx = (idx + 1) % Q->Capacity) {
printf("%d%s", Q->Array[idx], (i == Q->Size - 1) ? "\n" : ", ");
}
}
int main(void) {
Queue Q = CreateQueue(10);
Enqueue(Q, 1); Enqueue(Q, 2); Enqueue(Q, 3);
Enqueue(Q, 4); Enqueue(Q, 5); Enqueue(Q, 6);
ShowQueue(Q); // 1,2,3,4,5,6
Dequeue(Q); // 刪除 1
Enqueue(Q, 12); // 入隊 12
ShowQueue(Q); // 2,3,4,5,6,12
// 測試環形繞回
for (int i = 0; i < 5; i++) Dequeue(Q);
ShowQueue(Q); // 12
Enqueue(Q, 99);
ShowQueue(Q); // 12,99
return 0;
}