head==NULL 即為空。head 移至下一節點。引入一個不存資料的 head 節點,tail 指向最後一個有效節點。
空隊列:head->next == NULL 且 tail == head。
入隊:tail->next = new_node; tail = new_node;
出隊:tmp = head->next; head->next = tmp->next; if (!head->next) tail = head; free(tmp);
/*************************************************************************
> File Name: linkqueue.c
> Author: Baniel Gao
> Mail: createchance@163.com
> Blog: blog.csdn.net/createchance
> Created Time: Fri 20 Dec 2013 01:53:21 PM CST
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct {
int capacity;
int size;
Node *head; // 虛擬頭節點
Node *tail;
} LinkQueue;
Node *node_create(int val) {
Node *n = malloc(sizeof(Node));
n->data = val; n->next = NULL;
return n;
}
LinkQueue *lq_init(int cap) {
LinkQueue *q = malloc(sizeof(LinkQueue));
q->capacity = cap; q->size = 0;
q->head = node_create(0); // dummy
q->tail = q->head;
return q;
}
int lq_is_full(LinkQueue *q) { return q->size == q->capacity; }
int lq_is_empty(LinkQueue *q) { return q->size == 0; }
int lq_enqueue(LinkQueue *q, int val) {
if (lq_is_full(q)) return -1;
Node *n = node_create(val);
q->tail->next = n;
q->tail = n;
q->size++;
return 0;
}
int lq_dequeue(LinkQueue *q, int *out) {
if (lq_is_empty(q)) return -1;
Node *tmp = q->head->next;
*out = tmp->data;
q->head->next = tmp->next;
if (!q->head->next) q->tail = q->head; // 變空
free(tmp);
q->size--;
return 0;
}
void lq_free(LinkQueue *q) {
Node *cur = q->head;
while (cur) { Node *nxt = cur->next; free(cur); cur = nxt; }
free(q);
}
int main() {
LinkQueue *q = lq_init(10);
int val = 100;
while (lq_enqueue(q, val++) == 0);
int x;
while (lq_dequeue(q, &x) == 0) printf("%5d", x);
putchar('\n');
lq_free(q);
return 0;
}
100 101 102 103 104 105 106 107 108 109
| 特性 | 陣列循環隊列 | 鏈式隊列 |
|---|---|---|
| 容量 | 固定 | 動態(上限可設) |
| 記憶體 | 連續,預先配置 | 分散,按需配置 |
| 入隊/出隊 | O(1) 純索引運算 | O(1) 需 malloc/free |
| 快取友善 | 高 | 低 |
| 實作複雜度 | 中(環繞索引) | 低(指標直觀) |
tail = head,否則下次入隊會接在已釋放記憶體後 → 段錯誤。head->data 無意義,勿讀寫。NULL 回傳。