#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)或其他任何东西,你只要更改为相应的结构体即可。