#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
#define LEN 6 //定义队列的最大长度
#define true 1
#define false 0
typedef int bool;
//此队列为循环队列,基于数组实现
typedef struct Queue
{
int front;
int rear;
int * pBase;
}QUEUE,PQUEUE;
void init(QUEUE *);
bool en_queue(QUEUE *,int val);
void traverse_queue(QUEUE*);
bool full_queue(QUEUE *);
bool out_queue(QUEUE*,int *);
bool isempty_queue(QUEUE *);
//主函数
int main()
{
QUEUE Q;
init(&Q);
en_queue(&Q,1);
en_queue(&Q,2);
en_queue(&Q,3);
en_queue(&Q,4);
en_queue(&Q,5);
en_queue(&Q,6);
traverse_queue(&Q);
int val;
out_queue(&Q,&val);
printf("出队的元素为:%d\n",val);
traverse_queue(&Q);
out_queue(&Q,&val);
printf("出队的元素为:%d\n",val);
traverse_queue(&Q);
en_queue(&Q,3);
en_queue(&Q,4);
en_queue(&Q,5);
en_queue(&Q,6);
traverse_queue(&Q);
return 0;
}
//初始化一个队列
void init(QUEUE * pQ)
{
pQ->pBase = (int *)malloc(sizeof(int)*LEN);
pQ->front = pQ->rear = 0;
}
//入队操作
bool en_queue(QUEUE* pQ,int val)
{
if(full_queue(pQ))
{
return false;
}
else{
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear+1)%LEN;
}
}
//遍历队列中的元素
void traverse_queue(QUEUE* pQ)
{
if(isempty_queue(pQ))
return;
int i = pQ->front;
while(i!=pQ->rear)
{
printf("%d ",pQ->pBase[i]);
i = (i+1)%LEN;
}
printf("\n");
}
//判读队列是否已满
bool full_queue(QUEUE * pQ)
{
if((pQ->rear+1)%LEN == pQ->front)
return true;
else
return false;
}
//判断队列是否为空
bool isempty_queue(QUEUE *pQ)
{
if(pQ->front == pQ->rear)
return true;
else
return false;
}
//出队操作
bool out_queue(QUEUE* pQ ,int *pVal)
{
if(isempty_queue(pQ))
return;
*pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front+1)%LEN;
}
数据结构之——基于数组实现的循环队列
最新推荐文章于 2020-07-07 16:02:50 发布