我是靠谱客的博主 飘逸钢笔,这篇文章主要介绍C语言实现循环队列基本操作,现在分享给大家,希望可以做个参考。

循环队列依靠取模运算,实现队列中数据元素的逻辑成环操作。其相比队列的顺序存储实现,可以避免“假溢出”的问题。

头文件声明

复制代码
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
#include <stdio.h> #include <stdlib.h> /* * 循环队列实现 */ //数据元素上限 #define MaxSize 50 //定义数据类型 typedef int ElemType; /*结构体定义*/ typedef struct SqQueue { ElemType data[MaxSize];//数组-存放数据元素 int front, //队头指针 rear; //队尾指针 }SqQueue; //初始化队列 void InitQueue(SqQueue *q); //判断队列是否为空 int EmptyQueue(SqQueue q); //入队操作 int EnQueue(SqQueue *q,ElemType e); //出队操作 int DeQueue(SqQueue *q,ElemType* e); //获取队列长度 int LengthQueue(SqQueue q); //获取队头元素 void GetHead(SqQueue q,ElemType* e); //打印队列 void printSqQueue(SqQueue q);

函数实现

复制代码
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
#include "SqQueue.h" /** * 循环队列函数实现 */ //初始化队列 void InitQueue(SqQueue *q){ //队头指针-队尾指针,同时指向队首元素 q->front=q->rear=0; } //判断队列是否为空 int EmptyQueue(SqQueue q){ //队头指针和队尾指针指向同一个元素,则为空队列 return q.front==q.rear; } //入队操作 int EnQueue(SqQueue *q,ElemType e){ //判断是否队满 if ((q->rear+1)%MaxSize==q->rear) return -1; //入队操作 q->data[q->rear]=e;//添加数据元素-将队尾元素值置为e q->rear=(q->rear+1)%MaxSize;//尾指针向前移动,队尾指针++ return 1; } //出队操作 int DeQueue(SqQueue *q,ElemType* e){ //判断是否队空 if ((q->rear+1)%MaxSize==q->front) return -1; //保存数据 *e=q->data[q->front]; //出队操作 q->front=(q->front+1)%MaxSize; return 1; } //获取队列长度 int LengthQueue(SqQueue q){ return (q.rear-q.front+MaxSize)%MaxSize; } //获取队头元素 void GetHead(SqQueue q,ElemType* e){ //判断队列是否为空 if (q.front==q.rear) return; //获取队头元素的值 *e=q.data[q.front]; } //打印队列 void printSqQueue(SqQueue q){ //辅助指针 int pIndex; //打印队列元素 pIndex=q.front; while (pIndex<q.rear) { printf("%4d",q.data[pIndex++]); } printf("n"); }

函数测试

复制代码
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
#include "SqQueue.h" int main(int argc,char** argv){ //声明队列 SqQueue sQueue; int i; ElemType data; //初始化队列 InitQueue(&sQueue); //获取队头指针和队尾指针的值 printf("frontVal=%d,rearVal=%dn",sQueue.front,sQueue.rear); //判断队列是否为空 printf("is Empty?%dn",EmptyQueue(sQueue)); //入队操作 for (i=0;i<20;i++) { EnQueue(&sQueue,i+1); } //判断队列是否为空&获取队列长度 printf("is Empty?%d,len=%dn",EmptyQueue(sQueue),LengthQueue(sQueue)); //打印队列元素 printSqQueue(sQueue); //出队操作 DeQueue(&sQueue,&data); printf("the aimed value is %dn",data); //判断队列是否为空&获取队列长度 printf("is Empty?%d,len=%dn",EmptyQueue(sQueue),LengthQueue(sQueue)); //打印队列元素 printSqQueue(sQueue); //获取队头元素值 GetHead(sQueue,&data); printf("the head value is %dn",data); return 0; }

再贴个测试结果的图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是飘逸钢笔最近收集整理的关于C语言实现循环队列基本操作的全部内容,更多相关C语言实现循环队列基本操作内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部