存储结构
//循环队列的顺序存储结构
typedef struct {
QElemType data[MAXSIZES];
int front; // 头指针
int rear; // 尾指针,若队列不为空,指向队列元素的下一个位置
}SqQueue;
初始化操作
//初始化一个空队列Q
Status InitQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
return OK;
}
求队长
//返回Q的元素个数,也就是队列的当前长度
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXSIZES) % MAXSIZES;
}
入队操作
//入队操作
Status EnQueue(SqQueue *Q, QElemType e)
{
if ((Q->rear + 1) % MAXSIZES == Q->front) // 队列满的判断
return ERROR;
Q->data[Q->rear] = e; // 将元素e赋值给队尾
Q->rear = (Q->rear + 1) % MAXSIZES; // rear指针向后移动一个位置
// 若到最后则转到数组头部
return OK;
}
出队操作
//出队操作
Status DeQueue(SqQueue *Q, QElemType *e)
{
if (Q->front == Q->rear) // 队列空的判断
return ERROR;
*e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZES;
return OK;
}
实验结果
完整的代码
#include <stdio.h>
#define Status int
#define OK 1
#define ERROR 0
#define MAXSIZES 10
typedef int QElemType;
//循环队列的顺序存储结构
typedef struct {
QElemType data[MAXSIZES];
int front; // 头指针
int rear; // 尾指针,若队列不为空,指向队列元素的下一个位置
}SqQueue;
//初始化一个空队列Q
Status InitQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
return OK;
}
//返回Q的元素个数,也就是队列的当前长度
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXSIZES) % MAXSIZES;
}
//入队操作
Status EnQueue(SqQueue *Q, QElemType e)
{
if ((Q->rear + 1) % MAXSIZES == Q->front) // 队列满的判断
return ERROR;
Q->data[Q->rear] = e; // 将元素e赋值给队尾
Q->rear = (Q->rear + 1) % MAXSIZES; // rear指针向后移动一个位置
// 若到最后则转到数组头部
return OK;
}
//出队操作
Status DeQueue(SqQueue *Q, QElemType *e)
{
if (Q->front == Q->rear) // 队列空的判断
return ERROR;
*e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZES;
return OK;
}
int main()
{
SqQueue q;
InitQueue(&q);
printf("队列初始化成功!!!\n");
printf("插入2 4 6...\n");
EnQueue(&q, 2);
EnQueue(&q, 4);
EnQueue(&q, 6);
printf("插入成功,队列长度为 %d\n", QueueLength(q));
int a = 0, b = 0, c = 0;
DeQueue(&q, &a);
DeQueue(&q, &b);
DeQueue(&q, &c);
printf("队列中的元素为 %d %d %d\n", a, b, c);
return 0;
}
参考:
《大话数据结构》程杰著