一、解析
之所以叫队列,也是一个故名思意。排队中先进队伍的,顺序出去的,也就是从队头出去,而顺序的意思就是在内存结构中是顺序存放的,也就是数组。
二、存储结构
typedef struct{
QElemType *base;//基地址
int front;//队头
int rear;//队尾 总是指向队尾的空位置
}SqQueue;
三、操作
//===============顺序队列 循环队列============
#define MAXQSIZE 5
typedef struct{
QElemType *base;//基地址
int front;//队头
int rear;//队尾 总是指向队尾的空位置
}SqQueue;
Status InitQueue_Sq(SqQueue &Q){
Q.base = (QElemType*)malloc(sizeof(QElemType)*MAXQSIZE);
if (Q.base == NULL)
{
printf("分配失败");
return ERROR;
}
Q.front = 0;
Q.rear = 0;
return OK;
}
Status EnQueue_Sq(SqQueue &Q, QElemType e){
//进队e
//队列满了的情况
if ((Q.rear + 1) % MAXQSIZE == Q.front)
{
printf("队列满了");
return ERROR;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue_Sq(SqQueue &Q, QElemType &e){
//出队 赋值给e
//判断队列是否为空
if (Q.front == Q.rear)
{
//队列为空
printf("队列为空");
return ERROR;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
四、执行
//顺序队列
SqQueue q;
InitQueue_Sq(q);
EnQueue_Sq(q,1);
EnQueue_Sq(q, 2);
EnQueue_Sq(q, 3);
EnQueue_Sq(q, 4);
EnQueue_Sq(q, 5);
EnQueue_Sq(q, 6);
int e;
DeQueue_Sq(q,e);
printf("%d\n",e);
DeQueue_Sq(q, e);
printf("%d\n", e);
DeQueue_Sq(q, e);
printf("%d\n", e);
DeQueue_Sq(q, e);
printf("%d\n", e);
DeQueue_Sq(q, e);
printf("%d\n", e);
DeQueue_Sq(q, e);
printf("%d\n", e);