循环队列

循环队列

  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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值