循环队列的例程,大家共同学习
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
QUEUE QueueCreate(int size)
{
QUEUE q = (QUEUE)malloc(sizeof(*q));
if(q == NULL)
{
return NULL;
}
q->data = (QElement *)malloc(sizeof(QElement) * size);
if(q->data == NULL)
{
free(q);
return NULL;
}
q->capacity = size;
QueueMakeEmpty(q);
return q;
}
void QueueMakeEmpty(QUEUE q)
{
q->size = 0;
q->front = 1;
q->rear = 0;
}
int QueueIsEmpty(QUEUE q)
{
return (q->size == 0);
}
int QueueIsFull(QUEUE q)
{
return (q->size == q->capacity);
}
static int repeat(QUEUE q, int value)
{
if(++value == q->capacity)
value = 0;
return value;
}
int QueueEn(QUEUE q, const QElement *data)
{
if(QueueIsFull(q))
return -1;
q->rear = repeat(q, q->rear);
q->data[q->rear] = *data;
q->size++;
return 0;
}
int QueueDe(QUEUE q)
{
if(QueueIsEmpty(q))
return -1;
q->front = repeat(q, q->front);
q->size--;
return 0;
}
int QueueFront(QUEUE q, QElement *data)
{
if(QueueIsEmpty(q))
return -1;
*data = q->data[q->front];
return 0;
}
int QueueFrontAndDe(QUEUE q, QElement *data)
{
if(QueueFront(q, data) == 0)
return QueueDe(q);
return -1;
}
void QueueDispose(QUEUE q)
{
free(q->data);
free(q);
}
评论0
最新资源