循环队列练习
相关内容:
1.队列顺序存储的不足
2.循环队列(队列头尾相接的顺序存储结构)
//队列的初始化、入队、出队、取对头、计算队长度
#include<stdio.h>
#define MAXSIZE 10
typedef int Status;
#define OK 1
#define ERROR 0
typedef struct Queue
{
int data[MAXSIZE];
int front;//队头指针,指向队头元素
int rear;//队尾指针,指向队尾元素的下一个位置
}SqQueue;
Status InitQueue(SqQueue *SQ){
SQ->front=SQ->rear=0;
return OK;
}
//入队操作限定在队尾进行
Status EnQueue(SqQueue *SQ,int e){
if ((SQ->rear+1)%MAXSIZE==SQ->front)//判满
return ERROR;
SQ->data[SQ->rear]=e;//元素入队
SQ->rear=(SQ->rear+1)%MAXSIZE;//后移队尾指针,若越界则重回队头
return OK;
}
//出队操作限定在队头进行
Status DeQueue(SqQueue *SQ,int *e){
if (SQ->front==SQ->rear)//判空
return ERROR;
*e=SQ->data[SQ->front];
SQ->front=(SQ->front+1)%MAXSIZE;//后移队头指针,若越界则重回队头
return OK;
}
int GetHead(SqQueue *SQ){
if (SQ->front==SQ->rear)//判空
return ERROR;
return SQ->data[SQ->front];
}
int QueueLength(SqQueue *SQ){
return (SQ->rear - SQ->front+MAXSIZE)%MAXSIZE;
}
int main(){
int n,e;
SqQueue SQ;
InitQueue(&SQ);
printf("Init Completed!\n");
printf("输入入队元素个数:");
scanf("%d",&n);
for (size_t i = 0; i < n; i++)
{
printf("输入第%d个入队元素:",i+1);
scanf("%d",&e);
EnQueue(&SQ,e);
}
printf("队头元素:%d\n",GetHead(&SQ));
printf("当前队列长度:%d\n",QueueLength(&SQ));
for (size_t i = 0; i < n; i++)
{
printf("输入第%d个出队元素:",i+1);
DeQueue(&SQ,&e);
printf("%d\n",e);
}
return 0;
}