对重点的标注都在代码中,其中最为重要的内容为:
1.入队和出队的操作:(q->front+1)%MAXSIZE
(q->rear+1)%MAXSIZE
2.判满和判空:
------
队满:
队空
从逻辑上表示两者均是 front= rear ;所以为了区别两者我们需要队满的条件设置为:(q->rear+1)%MAXSIZE==q->front
3.队中 元素个数:(q->rear-q->front+MAXSIZE)%MAXSIZE
注:看图我们统一方向为:逆时针方向
对于图一来说:q->front 在 q->rear后面-------------为正常情况
所以 Length=q->rear-q-front (元素个数=尾数减头+1;但是q->front表示的是对头元素前一个位置~=自动-1)
对于图二来说:q->font 在 q->rear 前面---------------为特殊情况
所以此时 :q->front=q.front+MAXSIZE
所以 原始表达式子中 Length=q->rear-q-front=q.front+MAXSIZE-q->rear
综上所述:为了统一我们两式合并为 Length=q->rear-q-front=(q->rear-q.front+MAXSIZE)%MAXSIZE;
代码如下:
#define MAXSIZE 50
#define ElemType int
#include<stdio.h>
#include<Windows.h>
#include<string.h>
//循环队列结点说明
typedef struct Sq_Queue {
ElemType date[MAXSIZE];
int rear;
int front;
}SqQueue;
//初始化
void InitQueue(SqQueue*& q);
//销毁
void DestroyQueue(SqQueue*& q);
//判空
bool QueueEmpty(SqQueue* q);
//进队
bool enQueue(SqQueue*& q, ElemType e);
//出队
bool edQueue(SqQueue*& q, ElemType& e);
//队长度
bool QueueLength(SqQueue* q, int& a);
void InitQueue(SqQueue*& q)
{
q = (SqQueue*)malloc(sizeof(SqQueue));
q->front = q->rear = 0;
}
void DestroyQueue(SqQueue*& q)
{
free(q);
}
bool QueueEmpty(SqQueue* q)
{
return (q->front == q->rear);
}
bool enQueue(SqQueue*& q, ElemType e)
{
//进队之前先判满
if ((q->rear + 1) % MAXSIZE == q->front) {
return false;
}
q->rear = (q->rear + 1) % MAXSIZE;
/*
当队列中a[MAXISZE-1]处插完之后,a[0]处为空的话 可以从0开始再插,完美利用空间
*/
q->date[q->rear] = e;
return true;
}
bool edQueue(SqQueue*& q, ElemType& e)
{
//出队之前先判空
if (q->rear == q->front)
{
return false;
}
q->front = (q->front + 1) % MAXSIZE;
/*
当队列中a[MAXISZE-1]处插完之后,a[0]处为空的话 可以从0开始再插,完美利用空间
*/
e = q->date[q->front];
return true;
}
bool QueueLength(SqQueue* q, int& a)
{
//先判空
if (q->rear == q->front)
{
return false;
}
a = (q->rear - q->front + MAXSIZE) % MAXSIZE;
/*
正常状态下 :尾-初
当尾<初时:括号中值为负%操作下是一个错误答案
eg:一个长度为10的队列但是有效位置只有8-5则这个队列的长度为:7
(5-8)=-3%10=-3显然是错误的
(5-8+10)=7%10=7正解
*/
return true;
}
int main() {
SqQueue* q;
ElemType e[] = {1,2,3};
InitQueue(q);
QueueEmpty(q);
int s;
for (s = 0; s <= 3; ++s)
{
enQueue(q, e[s]);
}
ElemType w;
//edQueue(q, w);
//printf("%d", w);
int i;
QueueLength(q, i);
printf("\n%d", i);
return 0;
}