队列(Queue)是一种线性数据结构,遵循先进先出(First In, First Out, FIFO)原则。它类似于生活中排队等候的情景,最早进入队伍的人最先得到服务。队列在计算机科学中广泛应用于任务调度、消息传递、广度优先搜索(BFS)等领域。
基本概念
-
队头(Front):队列中最先入队的元素,也是队列中被允许出队的第一个元素。
-
队尾(Rear):队列中最后入队的元素,也是新元素入队的位置。
-
入队(Enqueue):将一个元素添加到队尾。
-
出队(Dequeue):移除队头元素并返回其值。若队列为空,则出队操作通常会触发错误或返回特定值表示队列已空。
-
队空(Empty Queue):当队列中没有元素时,称队列为空。
-
队满(Full Queue):对于有固定容量的队列,当无法再添加新元素时,称队列为满。动态分配空间的队列通常不会出现队满的情况。
-
队列的大小(Queue Size):当前队列中元素的数量。
队列的抽象数据类型(ADT)
1// 抽象数据类型定义
2typedef struct Queue Queue;
3
4// 创建一个空队列
5Queue* createQueue();
6
7// 销毁队列,并释放所有内存
8void destroyQueue(Queue* queue);
9
10// 判断队列是否为空
11bool isEmpty(Queue* queue);
12
13// 返回队列的大小(元素数量)
14int size(Queue* queue);
15
16// 将元素 item 入队
17void enqueue(Queue* queue, void* item);
18
19// 出队并返回队头元素的值。若队列为空,行为未在此处定义(可能抛出异常或返回特定值)
20void* dequeue(Queue* queue);
21
22// 查看队头元素但不出队。若队列为空,行为未在此处定义
23void* front(Queue* queue);
实现示例(基于数组)
1#include <stdio.h>
2#include <stdlib.h>
3
4#define QUEUE_SIZE 100
5
6typedef struct {
7 int items[QUEUE_SIZE];
8 int front;
9 int rear;
10} Queue;
11
12Queue* createQueue() {
13 Queue* queue = (Queue*) malloc(sizeof(Queue));
14 if (!queue) {
15 printf("Memory allocation failed.\n");
16 exit(1);
17 }
18 queue->front = -1; // 初始化为空队列
19 queue->rear = -1;
20 return queue;
21}
22
23void destroyQueue(Queue* queue) {
24 free(queue);
25}
26
27bool isEmpty(Queue* queue) {
28 return queue->front == -1;
29}
30
31int size(Queue* queue) {
32 return (queue->rear - queue->front + QUEUE_SIZE) % QUEUE_SIZE;
33}
34
35void enqueue(Queue* queue, int item) {
36 if ((queue->rear + 1) % QUEUE_SIZE == queue->front) {
37 printf("Queue overflow.\n");
38 exit(1);
39 }
40 queue->rear = (queue->rear + 1) % QUEUE_SIZE;
41 queue->items[queue->rear] = item;
42 if (queue->front == -1) {
43 queue->front = queue->rear; // 第一次入队时设置front
44 }
45}
46
47int dequeue(Queue* queue) {
48 if (isEmpty(queue)) {
49 printf("Queue underflow.\n");
50 exit(1);
51 }
52 int item = queue->items[queue->front];
53 queue->front = (queue->front + 1) % QUEUE_SIZE;
54 if (queue->front == queue->rear) {
55 queue->front = -1; // 清空队列时重置front和rear
56 queue->rear = -1;
57 }
58 return item;
59}
60
61int front(Queue* queue) {
62 if (isEmpty(queue)) {
63 printf("Queue is empty.\n");
64 exit(1);
65 }
66 return queue->items[queue->front];
67}
68
69int main() {
70 Queue* queue = createQueue();
71
72 enqueue(queue, 1);
73 enqueue(queue, 2);
74 enqueue(queue, 3);
75
76 printf("Dequeued: %d\n", dequeue(queue));
77 printf("Front element: %d\n", front(queue));
78
79 destroyQueue(queue);
80
81 return 0;
82}
队列因其简单且高效的特性,在编程中常用于实现任务调度、消息传递、广度优先搜索(BFS)等场景。队列的入队和出队操作的时间复杂度均为O(1),即常数时间复杂度。
收起