循环队列是使用得比较多的一种数据结构.关于循环队列的实现,有两件事要警惕.第一是检测队列是否为空,满的状态很重要.
第二某些程序设计人员使用不同的方法表示队列的队头和队尾.队列的大小是通过比较尾Rear和头Front隐式算出的.这是一种非常隐秘的
方法,因为存在某些特殊情形,因此如果你要修改这种方式编写的代码就要特别的仔细.下面是循环队列用数组方式的实现.
为了区分队列为空和为满这两种情况,定义了
循环队列为空:Rear与Front相差一个数组下标 ==> (Rear + 1)%N == Front 时为空,N为队列的长度
第二某些程序设计人员使用不同的方法表示队列的队头和队尾.队列的大小是通过比较尾Rear和头Front隐式算出的.这是一种非常隐秘的
方法,因为存在某些特殊情形,因此如果你要修改这种方式编写的代码就要特别的仔细.下面是循环队列用数组方式的实现.
为了区分队列为空和为满这两种情况,定义了
循环队列为空:Rear与Front相差一个数组下标 ==> (Rear + 1)%N == Front 时为空,N为队列的长度
循环队列为满:Rear与Front相差两个数组下标 ==> (Rear + 2)%N == Front 时为满,N为队列的长度
/* _Queue_h*/
#ifndef _Queue_h
#define _Queue_h
struct QueueRecord;
typedef struct QueueRecord *Queue;
typedef int ElementType;
int IsEmpty(Queue Q);
int IsFull(Queue);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
void EnQueue(ElementType X, Queue Q);
ElementType Front(Queue Q);
void Dequeue(Queue Q);
ElementType FrontAndDequeue(Queue Q);
#endif
/* _Queue_c*/
#include<stdio.h>
#include"queue.h"
#include<malloc.h>
#include"error.h"
struct QueueRecord
{
int Capacity;
int Front;
int Rear;
int Size;
ElementType *Array;
};
int IsEmpty(Queue Q)
{
return (Q->Rear + 1) % Q->Capacity == Q->Front;
}
int IsFull(Queue Q)
{
return (Q->Rear + 2)% Q->Capacity == Q->Front;
}
Queue CreateQueue(int MaxElements)
{
Queue Q = (Queue)malloc(sizeof(struct QueueRecord));
if(Q == NULL)
FatalError("Out of space!!");
Q->Array = (ElementType *)malloc(sizeof(struct QueueRecord) * MaxElements);
if(Q->Array == NULL)
FatalError("Out of space!");
Q->Capacity = MaxElements;
MakeEmpty(Q);
return Q;
}
void DisposeQueue(Queue Q)
{
if(Q != NULL)
{
free(Q->Array);
free(Q);
}
}
void MakeEmpty(Queue Q)
{
Q->Size = 0;
Q->Rear = 0;
Q->Front = 1;
}
void EnQueue(ElementType X, Queue Q)
{
if(IsFull(Q))
Error("Full queue");
else
{
Q->Size ++;
if( ++ Q->Rear == Q->Capacity )
Q->Rear = 0;
Q->Array[Q->Rear] = X;
}
}
ElementType Front(Queue Q)
{
if(!IsEmpty(Q))
return Q->Array[Q->Front];
Error("Queue is empty");
return 0;
}
void Dequeue(Queue Q)
{
if(IsEmpty(Q))
Error("queue is empty");
else
{
Q->Size --;
if(++ Q->Front == Q->Capacity)
Q->Front = 0;
}
}
ElementType FrontAndDequeue(Queue Q)
{
ElementType ret;
if(!IsEmpty(Q))
{
Q->Size --;
ret = Q->Array[Q->Front];
if(++ Q->Front == Q->Capacity)
Q->Front = 0;
return ret;
}
Error("queue is empty");
return 0;
}