使用数组创建队列
来源:互联网 发布:mac os maven环境变量 编辑:程序博客网 时间:2024/05/24 06:25
#include <stdlib.h>#include <stdio.h>#include <string.h>typedef struct queue{int queuesize; //数组的大小int head, tail; //队列的头和尾下标int *q; //数组头指针}Queue;/* initializztion */void InitQueue(Queue *q){if(0 == q->queuesize){q->queuesize = 8;}q->queuesize++;q->q = (int *)malloc(sizeof(int) * q->queuesize); //分配内存q->tail = 0;q->head = 0;}/* * if the queue is full, insertion will not be done and will return 0. * */int EnQueue(Queue *q, int key){if ((q->tail+1) % q->queuesize == q->head)//此时队列已满{//printf("the queue has been filled full!");return 0;}else{q->q[q->tail] = key;q->tail = (q->tail+1) % q->queuesize;return 1;}}/* * if the queue is empty, 0 will be always returned, so please check the queue is empty firstly. * */int DeQueue(Queue *q){int tmp = 0;if(q->tail == q->head) //判断队列不为空{//printf("the queue is NULL\n");}else{tmp = q->q[q->head];q->head = (q->head+1) % q->queuesize;}return tmp;}/* * if the queue is empty, 1 will be returned. * if the queue is not empty, 0 will be returned. * */int IsQueueEmpty(Queue *q){if(q->head == q->tail){return 1;}else{return 0;}}/* * if the queue is full, 1 will be returned. * if the queue is not full, 0 will be returned. * */int IsQueueFull(Queue *q){ if((q->tail+1)% q->queuesize == q->head) { return 1; } else { return 0; }}int GetQueueLen(Queue *q){return (q->queuesize - 1);}int GetQueueTail(Queue *q){return q->tail;}int GetQueueHead(Queue *q){return q->head;}int main(){int val;Queue q;memset(&q, 0, sizeof(Queue));InitQueue(&q);/*EnQueue(&q, 3);EnQueue(&q, 5);EnQueue(&q, 7);EnQueue(&q, 9);EnQueue(&q, 11);EnQueue(&q, 13);EnQueue(&q, 15);EnQueue(&q, 17);EnQueue(&q, 19);printf("\n0:%d, 1:%d,6:%d,7:%d\n", q.q[0], q.q[1], q.q[6], q.q[7]);while(IsQueueEmpty(&q)){val = DeQueue(&q);printf("Val=%d\n", val);}*/EnQueue(&q, 3);val = DeQueue(&q);printf("Val=%d\n", val);EnQueue(&q, 5);EnQueue(&q, 7);EnQueue(&q, 9);EnQueue(&q, 11);EnQueue(&q, 13);EnQueue(&q, 15);EnQueue(&q, 17);EnQueue(&q, 19);EnQueue(&q, 21);//printf("\n0:%d, 1:%d,6:%d,7:%d\n", q.q[0], q.q[1], q.q[6], q.q[7]);while(!IsQueueEmpty(&q)){val = DeQueue(&q);printf("Val=%d\n", val);}return 0;}
由于工作即将要用到循环队列来收取消息,所以整了一个,该代码已经经过简单测试了
这里用的纯c的,在VS2012测试通过,main部分不需要拷贝,只是一个简单用法
Queue结构中的数组q可以根据需要修改,如果你要存储消息(typeID+len+data)或其他任何东西,你只要更改为相应的结构体即可。
0 0
- 使用数组创建队列
- 使用数组实现队列
- 使用数组实现队列
- 使用数组实现队列
- 使用数组实现队列
- c语言静态数组创建队列
- java使用数组实现队列
- 创建和使用数组
- 使用new创建数组
- 循环队列拾遗-使用数组实现循环队列
- Java数据结构之队列-使用数组实现队列
- C#使用双堆栈创建队列
- C#使用双堆栈创建队列
- 消息队列创建以及使用示例
- 使用静态“环形”数组建立一个队列
- 使用数组实现双端队列
- 使用数组实现一个随机队列
- java使用数组实现优先级队列
- 详解Java GC的工作原理+Minor GC、FullGC
- 如何让ie兼容max-height,和min-height属性
- 【最大流】POJ-1459 Power Network
- 设计模式六大原则(3):依赖倒置原则
- How to Draw Waveform While Recording Using NAudio and WPF
- 使用数组创建队列
- 爱情,是什么!一个北大老师写的(将自己的心沉淀下来,用心看)
- PHP:exec与system区别
- Unidirectional TSP+uva+简单dp
- maven与checkstyle集成
- aspnet viewstate
- 【黑马程序员】黑马入学准备篇:Java高新技术之 JavaBean和BeanUtils
- c# 扩展方法
- maven与findbugs集成