队列 的顺序表示是用一组地址连续的存储单元依次存放队列中的
各个元素,并用指针front指向队头,指针rear指向队尾。
一般约定:front指针始终指向队头元素,而rear指针是指向队尾
元素的下一个位置。
假溢出:当队满的时候,若还有元素进队,rear指针将会越界,从而
导致程序出错。而此时又不易像顺序表那样扩大数组空间,因为队列
的实际可用空间并未装满。
处理假溢出:一种方法是将front指针和rear指针一起平移到数组的
起始位置;另一种方法就是将队列假想为一个循环的环状空间,称之
为循环队列。
循环队列的局限性:用户必须为它假设一个最大长度,若队列最大长度
无法估计,则不宜采用循环队列结构。
循环队列的类型定义及基本操作:
typedef struct
{
QElemType *base;
int front, rear;
}SqQueue;
初始化循环队列
int InitQueue(SqQueue &Q)
{
Q.base = (QElemType*)malloc(MaxQSize*sizeof(QElemType));
if (Q.base == NULL)
exit(OVERFLOW);
Q.front = Q.rear = 0;
return 0;
}
将循环队列清空
int ClearQueue(SqQueue &Q)
{
Q.front = Q.rear = 0;
}
求队列元素的个数
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MaxQSize) % MaxQSize;
}
插入元素到循环队列
int EnSqQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MaxQSize == Q.front)
return ERROR; //队列满
Q.base[Q.rear] = e; //元素e入队
Q.rear = (Q.rear + 1) % MaxQSize; //修改队尾指针
return OK;
}
从循环队列中删除元素
int DeSqueue(SqQueue &Q, QElemType &e)
{
if (Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front]; //取队头元素至e
Q.front = (Q.front + 1) % MaxQSize; //修改队头指针
return OK;
}
判断一个循环队列是否为空队列
int SqQueue(SqQueue Q)
{
if (Q.front == Q.rear)
return TRUE;
else
return FALSE;
}
//循环队列的简单操作
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define MaxQSize 10
typedef struct
{
int *base; //数据存储区起始地址
int front, rear; //队头、队尾元素所在单元号
}SqQueue;
int InitQueue(SqQueue &Q);
int ClearQueue(SqQueue &Q);
int QueueLength(SqQueue Q);
int EnSqQueue(SqQueue &Q, int e);
int DeSqQueue(SqQueue &Q, int &e);
int SqQueueEmpty(SqQueue Q);
int main(void)
{
int i, e;
SqQueue Q;
InitQueue(Q);
for (i=0; i<MaxQSize; i++) //只有MaxQSize-1个数据进队列
EnSqQueue(Q, i);
i = QueueLength(Q);
printf("队列里的元素有%d个\n", i);
for (i=0; i<3; i++)
{
DeSqQueue(Q, e);
printf("%d ", e);
}
printf("\n");
i = QueueLength(Q);
printf("队列里的元素有%d个\n", i);
for (i=10; i<12; i++)
EnSqQueue(Q, i);
i = QueueLength(Q);
printf("队列里的元素有%d个\n", i);
ClearQueue(Q);
i = QueueLength(Q);
printf("队列里的元素有%d个\n", i);
return 0;
}
int InitQueue(SqQueue &Q)
{
Q.base = (int *)malloc(MaxQSize*sizeof(int));
if (Q.base == NULL)
exit(1);
Q.front = Q.rear = 0;
return 0;
}
int ClearQueue(SqQueue &Q)
{
Q.front = Q.rear =0;
return 0;
}
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front +MaxQSize) % MaxQSize;
}
int EnSqQueue(SqQueue &Q, int e)
{
if ((Q.rear+1)%MaxQSize == Q.front)
return 1;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MaxQSize;
return 0;
}
int DeSqQueue(SqQueue &Q, int &e)
{
if (SqQueueEmpty(Q))
return 1;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MaxQSize;
return 0;
}
int SqQueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return 1;
return 0;
}