循环队列数组实现

循环队列的数组实现:

queue.h
#ifndef QUEUE_H
#define QUEUE_H

typedef
int ElementType;

struct QueueRecord;
typedef
struct QueueRecord *Queue;

int IsEmpty(Queue q);
int IsFull(Queue q);
Queue CreateQueue(
int maxElements);
void DisposeQueue(Queue q);
void MakeEmpty(Queue q);
int Enqueue(ElementType x, Queue q);
int Dequeue(Queue q);
ElementType Front(Queue q);
ElementType FrontAndDequeue(Queue q);

#endif
queue.c

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];
}

 

posted @ 2010-10-23 13:17  Linjian  阅读(948)  评论(0编辑  收藏  举报