先进先出的线性表,从队尾rear进,从队头front出
1.队列的顺序存储结构及实现
补充:判断循环队列队满和队空的三种方法
由于队满和对空时都有front==rear
,所以需要另想方法来区分队满和队空
方法一:通过length的大小来判断
队空的条件为length==0
队满的条件为length==MAXSIZE
方法二:少用一个元素空间
队空的条件为front==rear
队满的条件为(rear+1)%MAXSIZE==front
方法三:设置一个标志变量flag
队空时flag==0
,队不空时flag==1
队空的条件为flag==0
队满的条件为front==rear&&flag==1
1.1 循环队列的存储结构
方法一:
typedef struct
{
ElemType data[MAXSIZE];
int front; //指向队头元素
int rear; //指向队尾元素的下一个位置
int length;
}SqQueue;
方法二:
typedef struct
{
ElemType data[MAXSIZE];
int front;
int rear;
}SqQueue;
方法三:
typedef struct
{
ElemType data[MAXSIZE];
int front;
int rear;
int flag;
}SqQueue;
1.2 循环队列的基本操作
1.初始化InitQueue(Q)
方法一:
Status InitQueue(SqQueue *Q)
{
Q->front=Q->rear=0;
Q->length=0;
return OK;
}
方法二:
Status InitQueue(SqQueue *Q)
{
Q->front=Q->rear=0;
return OK;
}
方法三:
Status InitQueue(SqQueue *Q)
{
Q->front=Q->rear=0;
Q->flag=0;
return OK;
}
2.判断是否队空QueueEmpty(Q)
方法一:
Status QueueEmpty(SqQueue Q)
{
if(Q.length==0)
return TRUE;
else
return ERROR;
}
方法二:
Status QueueEmpty(SqQueue Q)
{
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}
方法三:
Status QueueEmpty(SqQueue Q)
{
if(Q.flag==0)
return TRUE;
else
return FALSE;
}
3.销毁DestroyQueue(Q)
与清空ClearQueue(Q)相同
4.清空ClearQueue(Q)
方法一:
Status ClearQueue(SqQueue *Q)
{
Q->front=Q->rear=Q->length=0;
return OK;
}
方法二:
Status ClearQueue(SqQueue *Q)
{
Q->front=Q->rear=0;
return OK;
}
方法三:
Status ClearQueue(SqQueue *Q)
{
Q->front=Q->rear=Q->flag=0;
return OK;
}
5.求长度QueueLength(Q)
方法一:
int QueueLength(SqQueue Q)
{
return Q.length;
}
方法二:
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
方法三:(同方法二)
6.取队头元素GetHead(Q,e)
方法一:
Status GetHead(SqQueue Q,ElemType *e)
{
if(Q.length==0)
return ERROR;
*e=Q.data[Q.front];
return OK;
}
方法二:
Status GetHead(SqQueue Q,ElemType *e)
{
if(Q.front==Q.rear)
return ERROR;
*e=Q.data[Q.front];
return OK;
}
方法三:
Status GetHead(SqQueue Q,ElemType *e)
{
if(Q.flag==0)
return ERROR;
*e=Q.data[Q.front];
return OK;
}
7.入队列(插入队尾)EnQueue(Q,e)
方法一:
Status EnQueue(SqQueue *Q,ElemType e)
{
if(Q->length==MAXSIZE)
return ERROR;
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE; //队尾指针指向下一个位置
Q->length++;
return OK;
}
方法二:
Status EnQueue(SqQueue *Q,ElemType e)
{
if ((Q->rear+1)%MAXSIZE == Q->front)
return ERROR;
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE;
return OK;
}
方法三:
Status EnQueue(SqQueue *Q,ElemType e)
{
if(Q->front==Q->rear&&Q->flag==1)
return ERROR;
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)