#include <stdio.h>
#include <stdlib.h>#define LENGTH 6 //设定循环队列长度为6,则有效数字是5个
typedef struct Queue
{
int * pArray; //队列元素首地址
int front; //队列的前面
int behind; //队列的后面
}QUEUE, * PQUEUE;void init_queue(PQUEUE); //创建,并初始化队列
bool empty_queue(PQUEUE); //检查队列是否为空
bool full_queue(PQUEUE); //检查队列是否已满
bool in_queue(PQUEUE, int); //入队
bool out_queue(PQUEUE, int *); //出队
void traversal_queue(PQUEUE); //遍历int main(void)
{
QUEUE Q;
int Val;init_queue(&Q);
in_queue(&Q, 1);
in_queue(&Q, 2);
in_queue(&Q, 3);
in_queue(&Q, 4);
in_queue(&Q, 5);
traversal_queue(&Q);
if(out_queue(&Q, &Val))
{
printf("出队成功,出队的数是:%d\n", Val);
}
else
{
puts("出队失败!\n");
}
traversal_queue(&Q);
return 0;
}
void init_queue(PQUEUE pQ)
{
pQ->pArray = (int *)malloc(sizeof(int) * LENGTH);
pQ->front = pQ->behind = 0;return;
}
bool empty_queue(PQUEUE pQ)
{
if(pQ->front == pQ->behind)
return true;
else
return false;
}
bool full_queue(PQUEUE pQ)
{
if((pQ->behind + 1) % LENGTH == pQ->front )
return true;
else
return false;
}
bool in_queue(PQUEUE pQ, int Val)
{
if(full_queue(pQ))
return false;
else
{
pQ->pArray[pQ->behind] = Val;
pQ->behind = (pQ->behind + 1) % LENGTH;
return true;
}
}
bool out_queue(PQUEUE pQ, int * pVal)
{
if(empty_queue(pQ))
return false;
else
{
*pVal = pQ->pArray[pQ->front];
pQ->front = (pQ->front + 1) % LENGTH;
return true;
}
}
void traversal_queue(PQUEUE pQ)
{
int f = pQ->front;while(f != pQ->behind)
{
printf("%d\t", pQ->pArray[f]);
f = (f + 1) % LENGTH;
}
puts("\n");
return;
}
一道循环队列例题
最新推荐文章于 2024-05-10 16:31:54 发布