#define QUEUE_TPYE char
#define QUEUE_LENGTH 512
#define CUSTOM_QUEUE_NAME myself_queue
#define LOOP_QUEUE //如果定义即为环形队列,不定义即为普通队列(会造成空间浪费)
struct queue
{
QUEUE_TPYE custom_queue[QUEUE_LENGTH];
int queue_head,queue_tail;
void (*queue_push)(struct queue * obj_queue,QUEUE_TPYE input);
QUEUE_TPYE (*queue_pop)(struct queue * obj_queue);
int (*is_queue_empty)(struct queue * obj_queue);
int (*is_queue_full)(struct queue * obj_queue);
};
void queue_push(struct queue * obj_queue,QUEUE_TPYE input);
QUEUE_TPYE queue_pop(struct queue * obj_queue);
int is_queue_empty(struct queue * obj_queue);
int is_queue_full(struct queue * obj_queue);
struct queue CUSTOM_QUEUE_NAME = {
.custom_queue=0,
.queue_head=0,
.queue_tail=0,
.queue_push=queue_push,
.queue_pop=queue_pop,
.is_queue_empty=is_queue_empty,
.is_queue_full=is_queue_full
};
void queue_push(struct queue * obj_queue,QUEUE_TPYE input)
{
obj_queue->custom_queue[obj_queue->queue_tail]=input;
#ifdef LOOP_QUEUE
obj_queue->queue_tail=(obj_queue->queue_tail+1)%QUEUE_LENGTH;
#else
CUSTOM_QUEUE_NAME.queue_tail++;
#endif
}
QUEUE_TPYE queue_pop(struct queue * obj_queue)
{
QUEUE_TPYE tmp=obj_queue->custom_queue[obj_queue->queue_head];
#ifdef LOOP_QUEUE
obj_queue->queue_head=(obj_queue->queue_head+1)%QUEUE_LENGTH;
#else
obj_queue->queue_head++;
#endif
return tmp;
}
int is_queue_empty(struct queue * obj_queue)
{
return obj_queue->queue_head == obj_queue->queue_tail;
}
int is_queue_full(struct queue * obj_queue)
{
#ifdef LOOP_QUEUE
return (obj_queue->queue_tail + 1) % QUEUE_LENGTH == obj_queue->queue_head;
#else
return (obj_queue->queue_tail - 1) == QUEUE_LENGTH;
#endif
}
int main()
{
CUSTOM_QUEUE_NAME.queue_push(&CUSTOM_QUEUE_NAME,'a');
CUSTOM_QUEUE_NAME.queue_push(&CUSTOM_QUEUE_NAME,'b');
printf("%c",CUSTOM_QUEUE_NAME.queue_pop(&CUSTOM_QUEUE_NAME));
printf("%c",CUSTOM_QUEUE_NAME.queue_pop(&CUSTOM_QUEUE_NAME));
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)