#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// 队列节点的结构体
typedef struct QueueNode {
int data;
struct QueueNode *next;
} QueueNode;
// 链队列的结构体
typedef struct LinkQueue {
QueueNode *front; // 队头指针
QueueNode *rear; // 队尾指针
int length; // 队列长度
} LinkQueue;
// 初始化队列
void InitQueue(LinkQueue *q) {
q->front = (QueueNode*)malloc(sizeof(QueueNode));
if (!q->front) {
exit(EXIT_FAILURE);
}
q->rear = q->front;
q->front->next = NULL;
q->length = 0;
}
// 入队
bool Enqueue(LinkQueue *q, int e) {
QueueNode *newNode = (QueueNode*)malloc(sizeof(QueueNode));
if (!newNode) {
exit(EXIT_FAILURE);
}
newNode->data = e;
newNode->next = NULL;
q->rear->next = newNode;
q->rear = newNode;
q->length++;
return true;
}
// 判断队列是否为空
bool IsEmpty(LinkQueue *q) {
return q->length == 0;
}
// 出队
bool Dequeue(LinkQueue *q, int *e) {
if (IsEmpty(q)) {
printf("队列是空的");
return false; // 队列为空,无法出队
}
QueueNode *temp = q->front->next;
*e = temp->data;
q->front->next = temp->next;
if (q->rear == temp) { // 如果出队的是最后一个节点
q->rear = q->front;
}
free(temp);
q->length--;
return true;
}
// 获取队列长度
int GetLength(LinkQueue *q) {
return q->length;
}
// 释放队列占用的内存
void FreeQueue(LinkQueue *q) {
QueueNode *current = q->front;
while (current != NULL) {
QueueNode *temp = current;
current = current->next;
free(temp);
}
q->front = q->rear = NULL;
q->length = 0;
}
// 测试代码
int main() {
// 声明一个LinkQueue类型的变量q
LinkQueue q;
// 初始化队列q
InitQueue(&q);
// 入队三个元素
Enqueue(&q, 1);
Enqueue(&q, 2);
Enqueue(&q, 3);
// 输出队列长度,应为3
printf("队列长度: %d\n", GetLength(&q)); // 输出: 3
// 声明一个整数e用于保存出队的元素
int e;
// 出队一个元素,并保存到e中
Dequeue(&q, &e);
// 输出出队的元素,应为1
printf("出队的元素: %d\n", e); // 输出: 1
// 输出队列长度,应为2
printf("队列长度: %d\n", GetLength(&q)); // 输出: 2
// 释放队列占用的内存
FreeQueue(&q);
// 程序正常结束
return 0;
}
运行结果: