我是靠谱客的博主 忐忑花卷,这篇文章主要介绍用最简单的数组去实现队列,现在分享给大家,希望可以做个参考。

用数组去实现队列

在上一节中我们是用数组去实现了客栈的功能,那么我们在这节中学习如何用数组去实现队列的功能

复制代码
1
2
3
4
队列是一种先进先出的数据结构(fisrt-in-first-out) 队列之允许在后端进行插入操作,在前端进行删除操作。 利用数组按下表进行顺序存储,删除,插入元素的特点,可在数组的末尾插入元素,在数组的首部删除元素,这样可以实现用数组实现队列的功能
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
头文件定义的代码: #ifndef __QUEUE_H_ #define __QUEUE_H_ #define MAX_NUM 100 int is_empty(); int is_full(); int pop_queue(); void push_queue(int element); int getQueueEnd(); int getQueueTop(); #endif
复制代码
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
queue.c文件的实现: #include"queue.h" int queueElements [MAX_NUM]; unsigned int position = 0; static void removeQueueTop(int index); int is_empty(){ return position == 0; } int is_full(){ return position >= MAX_NUM; } int pop_queue(){ if(is_empty()){ return 0; } int element = queueElements[0]; removeQueueTop(0); position--; return element; } static void removeQueueTop(int index){ int i; for(i= index; i< position-1 ; i++){ queueElements[i] = queueElements[i+1]; } } void push_queue(int element){ if(is_full()){ return;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
测试部分的代码: include<stdio.h> #include"queue.h" int main(int argc,char* argv []){ push_queue(2); push_queue(15); push_queue(17); push_queue(8); printf("%dn",pop_queue()); printf("%dn",pop_queue()); push_queue(100); printf("%dn",pop_queue()); return 0; }

最后的结果为:
2
15
17

注:小弟是一个C的初学者,如果有什么不对,或者需要指正的地方,请及时指正,以上两篇只是用最基础的C的数组来实现栈和队列,在后续会用指针的用法对其进行更深层次的优化。

最后

以上就是忐忑花卷最近收集整理的关于用最简单的数组去实现队列的全部内容,更多相关用最简单内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部