//队列
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Queue
{
int *pBase;
int front;//定义头结点
int rear;//定义尾结点
}QUEUE;
//函数声明
void init(QUEUE *);
bool en_queue(QUEUE *,int*);
void tarverse_queue(QUEUE *);
bool full_queue(QUEUE *);
bool out_queue(QUEUE *,int *);
//主程序
int main(void)
{
QUEUE Q;
int val;
init(&Q);
en_queue(&Q,1);
en_queue(&Q,2);
en_queue(&Q,3);
tarverse_queue(&Q);
if(out_queue(&Q,&val))
printf("出队成功,出队元素是:%d\n",val);
else
printf("出队失败!\n");
tarverse_queue(&Q);
return 0;
}
//初始化(定义循环队列长度为6)
void init(QUEUE *pQ)
{
pQ->pBase = (int *)malloc(sizeof(int) * 6);//初始化大小
pQ->front = 0;
pQ->rear = 0;
}
//判断是否已满
bool full_queue(QUEUE *pQ)
{
if ( (pQ->rear + 1) % 6 == pQ->front) //若队尾位置+1再与队列大小取余到达队首位置
return true;
else
return false;
}
//入队
bool en_queue(QUEUE *pQ,int val)
{
if (full_queue(pQ))
return true;
else
pQ->pBase[pQ->rear] = val;//入队的元素的位置为原队尾位置
pQ->rear = (pQ->rear + 1) % 6;
}
//遍历
void tarverse_queue(QUEUE *pQ)
{
int i = pQ->front;
while (i != pQ->rear)//只要i不指向队尾就输出
{
printf("%d ",pQ->pBase[i]);
i = (i+1) %6;
}
printf("\n");
}
//判断是否为空
bool empty_queue(QUEUE * pQ)
{
if (pQ->front == pQ->rear)//队首指针指向队尾指针
return true;
else
return false;
}
//出队
bool out_queue(QUEUE * pQ,int * pVal)
{
if (empty_queue(pQ))
return false;
else
* pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front + 1) % 6;//从队首出队,此时的队首为原来队首的下一个元素
return true;
}