入队:队尾指针加1取模,Q.rear=(Q.rear+1)%MaxSize;
出队:队头指针加1取模,Q.front=(Q.front+1)%MaxSize;
入队:队尾指针加1取模,Q.rear = (Q.rear + 1) % MaxSize;
队满:队尾指针加1取模等于队头指针,(Q.rear + 1) % MaxSize=Q.front;
队空:Q.front=Q.rear;
队中元素个数:(Q.rear-Q.front+MaxSize)%MaxSize;
***front指向的是队头元素,而rear指向的是队尾元素后的位置,为空;
代码段:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
#define MaxSize 50//定义队列的最大长长度度
#define ElemType int//把int命名为ElemType
typedef struct
{
ElemType data[MaxSize];//存放队列元素
int front,rear; //队头指针,队尾指针
}SqQueue;
void InitQueue(SqQueue& Q)//初始化队
{
Q.front = Q.rear = 0;//初始化队头队尾指针指向0
}
bool EmptyQueue(SqQueue Q)//判断队空
{
if (Q.front == Q.rear) //队空
return true;
else
return false;
}
bool EnQueue(SqQueue& Q, ElemType x)//入队操作
{
if ((Q.rear + 1) % MaxSize == Q.front)//队满报错
return false;
else
{
Q.data[Q.rear] = x;//入队
Q.rear = (Q.rear + 1) % MaxSize;//队尾指针加1取模
return true;
}
}
bool DeQueue(SqQueue& Q, ElemType& x)//出队
{
if (Q.front == Q.rear)//队空报错
return false;
else
{
x = Q.data[Q.front];//读取队头元素
Q.front = (Q.front + 1) % MaxSize;//队头指针加1取模
return true;
}
}
void GetQueue(SqQueue Q)//读取队头元素
{
if (Q.front == Q.rear)
printf("队空!\n");
else
{
printf("队头元素:%d", Q.data[Q.front]);
printf("\n");
}
}
int main()
{
SqQueue Q;
while (1)
{
printf("\n\n**********请输入接下来的操作:********\n");
printf("1:初始化队\n");
printf("2:入队\n");
printf("3:出队\n");
printf("4:读取队头元素\n");
printf("5:判断队空\n");
printf("-1:退出\n\n");
int count = 0;
ElemType x1 = 0, x2 = 0;
printf("操作:");
scanf_s("%d", &count);
if (count == -1)
break;
switch (count)
{
case 1:
InitQueue(Q);
break;
case 2:
printf("请输入入队元素:");
scanf_s("%d", &x1);
EnQueue(Q, x1);
break;
case 3:
DeQueue(Q, x2);
printf("出队元素为:%d", x2);
break;
case 4:
GetQueue(Q);
break;
case 5:
bool a;
a=EmptyQueue(Q);
if (a == false)
printf("队不为空!\n");
else
printf("队空!\n");
break;
}
}
}