循环队列(上课用)

源代码:

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef struct cycqueue
{
int data[MAXSIZE];
int front,rear; //声明队列的头指针和尾指针
}CycQue; //队列的数据类型


//初始化循环队列
void InitQueue(CycQue *CQ)
{
CQ->front=0;
CQ->rear=0;
}

//判断队列是否为空
int EmptyQueue(CycQue *CQ)
{
if(CQ->front==CQ->rear)
return 1; //队列为空,即为真
else
return 0;
}

 

//入队操作

int EnQueue(CycQue *CQ,int x)

{

if((CQ->rear+1) % MAXSIZE == CQ->front) //判断队列是否已满

{

printf("队列已满!\n");

return 0;

}

else

{

CQ->rear=(CQ->rear+1) % MAXSIZE;//如果队列没满,尾指针向后移动一个单元

CQ->data[CQ->rear]=x;

return 1;

}

}

 

//出队操作

void OutQueue(CycQue *CQ)

{

if(EmptyQueue(CQ)) //首先判断队列是否为空

{

printf("空队列!\n");

}

else

{

CQ->front=(CQ->front+1) % MAXSIZE;

}

}


//取栈顶元素

int GetHead(CycQue *CQ)

{

if(EmptyQueue(CQ))

return 0;

else

return CQ->data[(CQ->front+1) % MAXSIZE];

}

 

int main()

{

CycQue CQ;

CycQue *q=&CQ;

int i,n,e;

 

InitQueue(&CQ);

printf("\n向队列输入5个整数:\n");

for(i=0;i<5;i++)

{

scanf("%d",&n);

e=EnQueue(&CQ,n);

}

printf("\n出队顺序为:\n");
for(i=0;i<5;i++)

{

if(!EmptyQueue(&CQ)) //!代表非

{

n=GetHead(&CQ);

OutQueue(&CQ);

printf("%d ",n);

}

else

printf("\n空队列!\n");

}

return 0;

}

运行结果:

 

 

posted @ 2022-06-18 11:47  bobo哥  阅读(56)  评论(0)    收藏  举报