链表是一种动态数据结构,通过节点间的指针连接实现数据存储。队列是一种先进先出的线性结构,链表实现队列可以避免数组实现时的空间限制问题。
-
入队:从队尾加入
-
出队:从队首移除

一、数据结构定义
两个节点:
-
front:总指向第一个节点(出队端) -
rear:总指向最后一个节点(入队端)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node; //取别名
Node* front = NULL; // 队首指针
Node* rear = NULL; // 队尾指针
二、代码详解
2.1 入队操作(add_queue)
步骤:创建新节点 → 连接队尾 → 更新rear
void add_queue(int value) {
// 步骤1:创建新节点
// malloc分配内存,类似:新建一个"盒子"
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = value;
new_node->next = NULL;
// 步骤2:判断队列是否为空
if (rear == NULL) {
// 队列为空时,新节点既是队首也是队尾
front = new_node; // 队首指向新节点
rear = new_node; // 队尾也指向新节点
} else {
// 队列不为空时
rear->next = new_node; // 当前队尾的下一个指向新节点
rear = new_node; // 队尾指针更新为新节点
}
}
2.2 出队操作(del_queue)
步骤:保存front → 移动front → 检查是否变空 → 释放内存
int del_queue() {
// 步骤1:检查队列是否为空
if (front == NULL) {
return -1; // 队列为空
}
// 步骤2:保存要删除的节点
Node* temp = front; // temp指向队首
int value = temp->data; // 保存数据
// 步骤3:移动front指针
front = front->next; // front指向下一个节点
// 步骤4:如果出队后队列为空,重置rear
if (front == NULL) {
rear = NULL;
}
// 步骤5:释放内存
free(temp);
return value;
}
2.3 打印队列(print_queue)
void print_queue() {
if (front == NULL) {
printf("队列为空!\n");
return;
}
Node* current = front; // 从队首开始
while (current != NULL) {
printf("%d ", current->data);
current = current->next; // 移动到下一个节点
}
printf("\n");
}
2.4 清空队列(clear_queue)
void clear_queue() {
while (front != NULL) {
del_queue();
}
printf("队列已清空!\n");
}
2.4 主函数main
int main() {
int a, b, c;
a = 10;
b = 20;
c = 30;
printf("=== 链表实现队列测试 ===\n\n");
// 测试入队
printf("1. 测试入队操作:\n");
add_queue(a);
add_queue(b);
add_queue(c);
print_queue();
// 测试获取队首
printf("\n2. 获取队首元素:%d\n", get_front());
// 测试出队
printf("\n3. 测试出队操作:\n");
del_queue();
print_queue();
// 继续入队
printf("\n4. 继续入队:\n");
add_queue(40);
add_queue(50);
print_queue();
// 出队所有元素
printf("\n5. 出队所有元素:\n");
while (front != NULL) {
del_queue();
}
print_queue();
// 测试空队列操作
printf("\n6. 测试空队列操作:\n");
del_queue(); // 应该提示队列为空
return 0;
}
三、运行结果

1334

被折叠的 条评论
为什么被折叠?



