循环队列

来源:互联网 发布:js设置属性值 编辑:程序博客网 时间:2024/04/29 00:03

循环队列

  1. 队列是一种”先进先出”的数据结构
  2. 静态队列一定是循环队列
  3. 静态队列的核心是数组
/*    ********************循环队列*********************/# 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;    }}
1 0
原创粉丝点击