- UID
- 1029342
- 性别
- 男
|
#include <stdio.h>
#include "ringq.h"
int ringq_init(RINGQ * p_queue)
{
p_queue->size = QUEUE_MAX ;
p_queue->head = 0;
p_queue->tail = 0;
p_queue->tag = 0;
return 0;
}
int ringq_free(RINGQ * p_queue)
{
return 0;
}
int ringq_push(RINGQ * p_queue,int data)
{
print_ringq(p_queue);
if(ringq_is_full(p_queue))
{
printf("ringq is full\n");
return -1;
}
p_queue->space[p_queue->tail] = data;
p_queue->tail = (p_queue->tail + 1) % p_queue->size ;
/* 这个时候一定队列满了*/
if(p_queue->tail == p_queue->head)
{
p_queue->tag = 1;
}
return p_queue->tag ;
}
int ringq_poll(RINGQ * p_queue,int * p_data)
{
print_ringq(p_queue);
if(ringq_is_empty(p_queue))
{
printf("ringq is empty\n");
return -1;
}
*p_data = p_queue->space[p_queue->head];
p_queue->head = (p_queue->head + 1) % p_queue->size ;
/* 这个时候一定队列空了*/
if(p_queue->tail == p_queue->head)
{
p_queue->tag = 0;
}
return p_queue->tag ;
}
测试代码
[cpp] view plain copy
print?
/* 测试第一种环形队列*/
void test5()
{
RINGQ rq, * p_queue;
int i,data;
p_queue = &rq;
ringq_init(p_queue);
for(i=0; i < QUEUE_MAX +2 ; i++)
{
ringq_push(p_queue,i+1);
}
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
ringq_free(p_queue);
}
/* 测试第一种环形队列,更加复杂的情况*/
void test6()
{
RINGQ rq, * p_queue;
int i,data;
p_queue = &rq;
ringq_init(p_queue);
ringq_push(p_queue,1);
ringq_push(p_queue,2);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
ringq_push(p_queue,3);
ringq_push(p_queue,4);
ringq_push(p_queue,5);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
ringq_push(p_queue,6);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
if(ringq_poll(p_queue,&data)>=0)
PRINT_INT(data);
ringq_free(p_queue);
} |
|