为充分利用向量空间,克服假溢出现象的方法是:将向量空间想象为一个首尾相接的圆环,并称这种向量为循环向量。存储在其中的队列称为循环队列(Circular Queue)。循环队列是把顺序队列首尾相连,把存储队列元素的表从逻辑上看成一个环,成为循环队列。
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
#define ERROR 1
#define OK 0
typedef int Status;
typedef int QueueElemType;
typedef enum { false, true } bool;
typedef struct
{
QueueElemType *data;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue **pQ);
Status DestoryQueue(SqQueue *Q);
Status ClearQueue(SqQueue *Q);
bool QueueEmpty(SqQueue *Q);
bool QueueFull(SqQueue *Q);
Status GetHead(SqQueue *Q, QueueElemType *e);
Status EnQueue(SqQueue *Q, QueueElemType e);
Status DeQueue(SqQueue *Q, QueueElemType *e);
void PrintALLQueue(SqQueue *Q);
void PrintQueue(SqQueue *Q);
int main()
{
int status = -1;
SqQueue *Q = NULL;
status = InitQueue(&Q);
if (status == ERROR)
{
printf("func InitQueue() error!\n");
}
PrintALLQueue(Q);
PrintQueue(Q);
int choice = -1;
int e = 0;
while (1)
{
printf("1 添加 2 删除 0 退出\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Please enter e:");
scanf("%d", &e);
status = EnQueue(Q, e);
if (status == ERROR)
{
printf("FULL!\n");
}
PrintALLQueue(Q);
PrintQueue(Q);
break;
case 2:
status = DeQueue(Q, &e);
if (status == ERROR)
{
printf("EMPTY!\n");
}
else
printf("The number is %d.\n", e);
PrintALLQueue(Q);
PrintQueue(Q);
break;
case 0:exit(0);
}
}
DestoryQueue(Q);
Q = NULL;
return 0;
}
Status InitQueue(SqQueue **pQ)
{
SqQueue *Q;
Q = (SqQueue*)malloc(sizeof(SqQueue));
if(Q == NULL)
{
printf("分配内存失败!\n");
return ERROR;
}
Q->data = (QueueElemType*)malloc(MAXSIZE * sizeof(QueueElemType));
if (Q->data == NULL)
{
printf("分配内存失败!\n");
return ERROR;
}
Q->front = 0;
Q->rear = 0;
*pQ = Q;
return OK;
}
Status DestoryQueue(SqQueue *Q)
{
if (Q->data != NULL)
{
free(Q->data);
Q->data = NULL;
return OK;
}
else
return ERROR;
}
Status ClearQueue(SqQueue *Q)
{
Q->front = 0;
Q->rear = 0;
return OK;
}
bool QueueEmpty(SqQueue *Q)
{
if (Q->front == Q->rear)
return true;
else
return false;
}
bool QueueFull(SqQueue *Q)
{
if ((Q->rear + 1) % MAXSIZE == Q->front)
return true;
else
return false;
}
Status GetHead(SqQueue *Q, QueueElemType *e)
{
if (QueueEmpty(Q) == true)
{
return ERROR;
}
else
*e = Q->data[Q->front];
return OK;
}
Status EnQueue(SqQueue *Q, QueueElemType e)
{
if (QueueFull(Q) == true)
return ERROR;
Q->data[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE;
return OK;
}
Status DeQueue(SqQueue *Q, QueueElemType *e)
{
if (QueueEmpty(Q) == true)
{
return ERROR;
}
*e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return OK;
}
Status QueueLength(SqQueue *Q, int *length)
{
*length = (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
return OK;
}
void PrintALLQueue(SqQueue *Q)
{
for (int i = 0; i < MAXSIZE; i++)
{
printf("%d ", Q->data[i]);
}
putchar('\n');
}
void PrintQueue(SqQueue *Q)
{
int status = -1;
int length = 0;
QueueLength(Q, &length);
for (int i = 0; i < length; i++)
{
printf("%d ", (Q->data[(Q->front + i) % MAXSIZE]));
}
putchar('\n');
}