队列(Queue)是一种特殊类型的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。队列中没有元素时,称为空队列。队列的数据元素又称为队列元素。在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以又称为先进先出(FIFO—first in first out)线性表。
在计算机科学中,队列的主要用途是存储等待处理的元素,例如等待打印的任务、等待CPU处理的线程等。队列的一个重要性质是:队列中的元素保持原有的顺序。队列的实现方式有多种,包括基于数组和基于链表的实现。
以下是一个简单的基于链表的队列实现的示例
#include <stdio.h>
#include <stdlib.h>
// 定义队列节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义队列结构体
typedef struct Queue {
Node* front; // 队列头
Node* rear; // 队列尾
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->front = q->rear = NULL;
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->front == NULL;
}
// 入队操作
void enqueue(Queue* q, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队操作
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
Node* temp = q->front;
int value = temp->data;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return value;
}
// 打印队列
void printQueue(Queue* q) {
Node* temp = q->front;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 清理队列内存
void freeQueue(Queue* q) {
Node* temp;
while (q->front != NULL) {
temp = q->front;
q->front = q->front->next;
free(temp);
}
q->rear = NULL;
}
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printQueue(&q); // 输出: 1 2 3
printf("Dequeued element: %d\n", dequeue(&q)); // 输出: 1
printQueue(&q); // 输出: 2 3
freeQueue(&q);
return 0;
}
这段代码首先定义了一个Node
结构体来表示队列中的每个节点,然后定义了一个Queue
结构体来表示整个队列。接着,我们实现了队列的初始化、判断是否为空、入队、出队、打印和清理内存的函数。最后,在main
函数中,我们创建了一个队列,并对其进行了一些基本操作来展示其功能。