首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

隊列數據結構全解析:鏈隊列、循環隊列 C 語言完整實現

     編輯:關於C語言

隊列數據結構全解析:鏈隊列、循環隊列 C 語言完整實現

隊列(FIFO)是受限線性表,僅允許隊尾入隊、隊頭出隊。本文實現鏈式與循環順序兩種存儲結構。

一、鏈隊列

帶頭結點單鏈表,頭/尾指針分別指向頭結點/尾節點。

typedef struct Node { int data; struct Node *next; } Node, *Queue;
typedef struct { Queue front, rear; } LinkQueue;

void initQueue(LinkQueue *q) {
    q->front = q->rear = malloc(sizeof(Node));
    q->front->next = NULL;
}
bool isEmpty(LinkQueue q) { return q.front == q.rear; }

void insertQueue(LinkQueue *q, int val) {
    Node *n = malloc(sizeof(Node));
    n->data = val; n->next = NULL;
    q->rear->next = n; q->rear = n;
}
void deleteQueue(LinkQueue *q) {
    if (isEmpty(*q)) return;
    Node *n = q->front->next;
    q->front->next = n->next;
    if (q->rear == n) q->rear = q->front;  // 刪除最後一個
    free(n);
}

二、循環隊列(順序存儲)

固定大小數組,front 指向隊頭,rear 指向隊尾**下一位置**。犧牲一個單元區分空/滿。

#define MAX_SIZE 5
typedef struct { int *base; int front, rear; } CircularQueue;

void initQueue(CircularQueue *q) {
    q->base = malloc(MAX_SIZE * sizeof(int));
    q->front = q->rear = 0;
}
int getLength(CircularQueue q) {
    return (q.rear - q.front + MAX_SIZE) % MAX_SIZE;
}
void insertQueue(CircularQueue *q, int e) {
    if ((q->rear + 1) % MAX_SIZE == q->front) { puts("Full"); return; }
    q->base[q->rear] = e;
    q->rear = (q->rear + 1) % MAX_SIZE;
}
void deleteQueue(CircularQueue *q) {
    if (q->front == q->rear) { puts("Empty"); return; }
    q->front = (q->front + 1) % MAX_SIZE;
}

測試結果

循環隊列初始化:長度 0
入隊 0,1,2,3 → 遍歷: 0 1 2 3
再入隊 4 → Full (犧牲一格)
出隊 0 → 1 2 3
出隊 1 → 2 3
出隊 2 → 3
出隊 3 → Empty

對比總結

掌握兩種實現,可根據場景選擇最適隊列結構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性鏈隊列循環隊列
空間動態分配,無上限固定大小,需預知最大長度
入隊永不滿(除非 OOM)可能滿,需判滿
出隊需 free,指針操作僅移動索引,極快
適用長度不可預知、頻繁增減高性能固定緩衝區、嵌入式