您的位置:首页 > 理论基础 > 数据结构算法

循环队列

2016-04-28 23:09 471 查看

循环队列

队列是一种”先进先出”的数据结构

静态队列一定是循环队列

静态队列的核心是数组

/*
********************循环队列********************
*/
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
//定义队列的数据类型(可以参考构造数组这个数据结构来学习构造队列)
typedef struct Queue
{
int * pBase;//队列的基址
int front;//队首
int rear;//队尾

}QUEUE,* PQUEUE;
//函数声明最好不加变量名字这样声明意图更清晰
void init_queue(PQUEUE);
bool entry_queue(PQUEUE,int);
bool full_queue(PQUEUE);
void traverse_queue(PQUEUE);
bool empty_queue(PQUEUE);
bool out_queue(PQUEUE,int *);

int main(void)
{
QUEUE Q;
int val;
//初始化队列
init_queue(&Q);
//入队
entry_queue(&Q,1);
entry_queue(&Q,2);
entry_queue(&Q,3);
entry_queue(&Q,4);
entry_queue(&Q,5);
printf("遍历输出:");
traverse_queue(&Q);
//出队
if(!out_queue(&Q,&val))
{
printf("OutQueue is failed!\n");
}
else
{
printf("出队元素: val = %d\n",val);
printf("遍历输出:");
traverse_queue(&Q);
}

return 0;
}
//初始化队列
void init_queue(PQUEUE pQ)
{
pQ->pBase = (int *)malloc(sizeof(int)*5);//初始化基址;数组的长度是5但它的有效长度是4
if(NULL == pQ->pBase)//如果地址为空则退出程序
{
exit(-1);
}
else
{
pQ->front = 0;//初始化队首
pQ->rear = 0;
return;
}

}
//队列是否满
bool full_queue(PQUEUE pQ)
{
if((pQ->rear+1) % 5 == pQ->front)//队尾的下一个存储单元和队首相等
{
return true;
}
else
{
return false;
}
}
//入队[从队首插入]
bool entry_queue(PQUEUE pQ,int val)
{
if(full_queue(pQ))
{
return false;
}
else
{
pQ->pBase[pQ->rear] = val;//从队尾插入
pQ->rear = (pQ->rear+1) % 5;//队尾下移

return true;
}
}
//遍历队列
void traverse_queue(PQUEUE pQ)
{
int i = pQ->front;//不能直接操作pQ->front否则会影响改变pQ->front的值从而影响下面的操作

while(i != pQ->rear)
{
printf("%-3d",pQ->pBase[i]);//输出队首
i = (i+1) % 5;//队首下移
}
printf("\n\n");

return;
}
//队列是否空
bool empty_queue(PQUEUE pQ)
{
if(pQ->rear == pQ->front)//队首与队尾相等类似于初始化是两者就是相等的那时候队列就是空的
{
return true;
}
else
{
return false;
}
}
//出队[从队首删除]
bool out_queue(PQUEUE pQ,int * pVal)
{
if(empty_queue(pQ))
{
return false;
}
else
{
* pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front+1) % 5;

return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息