您的位置:首页 > 其它

循环队列数组实现

2010-10-23 13:17 495 查看
循环队列的数组实现:

queue.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "queue.h"

#define SAFE_FREE(q) {if (q) {free(q); q = NULL;}}

struct QueueRecord
{
int capacity;
int front;
int rear;
int size;
ElementType *array;
};

int IsEmpty(Queue q)
{
return q->size == 0;
}

int IsFull(Queue q)
{
return q->size == q->capacity;
}

Queue CreateQueue(int maxElements)
{
Queue q = malloc(sizeof(struct QueueRecord));
if (q == NULL)
{
fprintf(stderr, "create queue failed.");
return NULL;
}
q->array = malloc(maxElements * sizeof(char));
if (q->array == NULL)
{
fprintf(stderr, "create queue failed.");
return NULL;
}
q->capacity = maxElements;
q->front = q->rear = 0;
q->size = 0;

return q;
}

void DisposeQueue(Queue q)
{
if (q == NULL)
{
fprintf(stderr, "the queue is NULL.");
return;
}
SAFE_FREE(q->array);
SAFE_FREE(q);
}

void MakeEmpty(Queue q)
{
if (q == NULL)
{
fprintf(stderr, "the queue is NULL.");
return;
}
q->front = q->rear = 0;
q->size = 0;
memset(q->array, 0x00, q->capacity);
}

int Enqueue(ElementType x, Queue q)
{
if (IsFull(q))
{
fprintf(stderr, "queue is full.");
return -1;
}
if (IsEmpty(q))
{
q->array[q->front] = x;
}
else
{
if ((q->rear + 1) == q->capacity)
{
q->rear = 0;
q->array[q->rear] = x;
}
else
{
q->array[++q->rear] = x;
}
}
q->size++;
printf("size = %d\n", q->size);

return 0;
}

int Dequeue(Queue q)
{
if (IsEmpty(q))
{
fprintf(stderr, "queue is empty.");
return -1;
}

q->array[q->front] = 0;
if ((q->front + 1) == q->capacity)
{
q->front = 0;
}
else
{
q->front++;
}
q->size--;
return 0;
}

ElementType Front(Queue q)
{
if (q == NULL)
{
fprintf(stderr, "queue is empty.");
return -1;
}
return q->array[q->front];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: