我是靠谱客的博主 知性蚂蚁,这篇文章主要介绍循环队列_数组实现,现在分享给大家,希望可以做个参考。

循环队列是指, 队尾指针走到末尾后, 还可以继续从头开始走.

front指针仍然是指向第一个元素的前一个元素, rear指针指向最后一个元素.
下面我们重点讨论一下循环队列如何判断空和满的问题?
我下面判断队列空和满是直接根据q->length属性来判断, 当q->length为0,
表示队列为空, 当q->length = maxSize - 1时, 队列为满. 由于遍历上的原因,
队列的最大长度只能是数组最大长度-1.

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h> #include <stdlib.h> struct queue { int* data; int front; int rear; int maxSize; int length; }; typedef struct queue node; typedef struct queue* link; // 函数声明 link createQueue (int maxSize); void printQueue (link q); int add (link q, int x); int del (link q); int main () { int i; int maxSize = 10; // 队列的最大长度 link qhead = createQueue(maxSize); // 初始队列信息 printQueue(qhead); // 基本入队测试 for (i=1; i<=10; i++) { add(qhead, i * 2); } printQueue(qhead); // 基本出队测试 del(qhead); del(qhead); del(qhead); del(qhead); printQueue(qhead); // 循环入队测试 add(qhead, 100); add(qhead, 200); add(qhead, 300); add(qhead, 400); add(qhead, 500); printQueue(qhead); return 0; } // 创建空队列 link createQueue (int maxSize) { link q; q = (node*)malloc(sizeof(node)); q->data = (int*)malloc(sizeof(int) * maxSize); q->front = -1; q->rear = -1; q->length = 0; q->maxSize = maxSize; return q; } // 打印 void printQueue (link q) { int i; printf("当前队列的信息如下: n"); printf("front = %dn", q->front); printf("rear = %dn", q->rear); printf("length = %dn", q->length); printf("maxSize = %dn", q->maxSize); // 打印队列中的数据 if (q->length == 0) { printf("当前队列中没有数据n"); } else { printf("队列中的数据如下: n"); i = q->front; while (i != q->rear) { i = (i + 1) % q->maxSize; printf("%d %dn", i, q->data[i]); } } printf("n"); } // 入队 int add (link q, int x) { if (q->length == q->maxSize -1 ) { printf("队列已满, 不能入队n"); return 0; } q->rear = (q->rear + 1) % q->maxSize; q->data[q->rear] = x; q->length++; return 1; } // 出队 // 错误返回0, 正确返回被出队元素的值 int del (link q) { if (q->length == 0) { printf("队列为空, 不能出队n"); return 0; } q->front = (q->front + 1) % q->maxSize; q->length--; return q->data[q->front]; }

转载于:https://www.cnblogs.com/asheng2016/p/7615741.html

最后

以上就是知性蚂蚁最近收集整理的关于循环队列_数组实现的全部内容,更多相关循环队列_数组实现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部