#include<stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERLOW -1
#define MAXQSIZE 100
typedef int QElemType;
typedef struct{
QElemType *base;
QElemType data[MAXQSIZE];
int front;
int rear;
}SqQueue;
//初始化
int InitQUeue(SqQueue &Q){
Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));//为队列分配一个最大容量为MAXSIZE的数组空间
if(!Q.base)exit(OVERLOW);//储存分配失败
Q.front=Q.rear=0;//头指针=尾指针=0;
return OK;
}
//入列
int EnQueue(SqQueue &Q,QElemType e){
if((Q.rear+1)%MAXQSIZE==Q.front)return ERROR;//判断是否为满列
Q.base[Q.rear]=e;//新元素插入队尾
Q.rear=(Q.rear+1)%MAXQSIZE;//依次入列 ,指针+1
return OK;
}
//长度
int QueueLength(SqQueue Q){
return((Q.rear-Q.front+MAXQSIZE)%MAXQSIZE);//返回队列长度
}
//取列头元素
int GetHead(SqQueue &Q,QElemType &e){
if(Q.front!=Q.rear){//判断队列是否为空
e=Q.base[Q.front];//取队头元素元素,队头指针保持不变
return OK;
}else{
return ERROR;
}
}
//出列
int DEQueue(SqQueue &Q,QElemType &e){
if(Q.front==Q.rear)return ERROR;//判断是否为空队列
e=Q.base[Q.front];//保存对头元素
Q.front=(Q.front+1)%MAXQSIZE;//依次出列
return OK;
}
int main(){
SqQueue Q;
Q.front=0;
Q.rear=0;
Q.data[Q.rear]=1;
Q.rear=(Q.rear+1)%MAXQSIZE;
Q.data[Q.rear]=2;
Q.rear=(Q.rear+1)%MAXQSIZE;
int Length=QueueLength(Q);
printf("循环队列的长度为:%d\n",Length);
if(InitQUeue(Q)){
printf("循环队列初始化完成\n");
if(EnQueue(Q,1)){
printf("循环队列1入队成功\n");
QElemType GEte;
if(GetHead(Q,GEte)){
printf("循环队列头元素为:%d\n",GEte);
}else{
printf("循环队列为空,无法获取队头元素\n");
}
QElemType e;
if(DEQueue(Q,e)){
printf("循环队列e出队成功\n");
}else{
printf("循环队列e出队失败\n");
}
}else{
printf("循环队列入队失败\n");
}
}else{
printf("循环队列初始化失败\n");
}
return 0;
}
循环队列的基本操作
最新推荐文章于 2024-07-01 22:13:40 发布
本文介绍了如何使用C语言实现循环队列的数据结构,包括初始化、入队(EnQueue)、出队(DEQueue)以及队列长度的计算。通过示例展示了循环队列的操作过程。
摘要由CSDN通过智能技术生成