c语言 数据结构 栈 循环队列

循环队列

循环队列要留一个空间:front = rfter + 1, 要不然,头等于尾就等于空了

如果需要一直在循环队列里面的就需要取余, f最多为4,(4 + 1 )% 5 = 0, 所以每次到4之后就取余,让他重行变为0

构成队列结构体要素:数组, front rear;

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define SIZE 20
typedef struct queue
{
    int data[SIZE];
    int front; // front front front
    int rear;  // after after after after
} sl, *que;

// 初始化节点
que Her_a(void)
{
    que queue = malloc(sizeof(sl));
    if (queue == NULL)
    {
        printf("queue erreo\n");
        return NULL;
    }
    queue->front = 0;
    queue->rear = 0;
    return queue;
}

// 入队
int Mak_a(que queue, int num)
{
    if ((queue->rear + 1) % SIZE == queue->front)
    {
        printf("队列已满\n");
        return -1;
    }
    else
    {
        //添加数据
        queue->data[queue->rear] = num;
        //重置队尾, 如果前面的删掉了后面的可以插过去
        queue->rear = (queue->rear + 1) % SIZE;
    }
}

//出队
int Mak_b(que queue, int *num)
{
    //如果头和尾想连就是空表
    if (queue->front == queue->rear)
    {
        printf("队列为空\n");
        return -1;
    }
    else
    {
        *num = queue->data[queue->front];
        queue->front = (queue->front + 1) % SIZE;
    }
}

int main(int argc, char const *argv[])
{
    que myqueue = Her_a();

    //入队
    printf("入队");
    for (int i = 1; i <= 10; i++)
    {
        Mak_a(myqueue, i);
        printf("-%d", i);
    }

    printf("\n");
    printf("出队");
    int num;

    for (int i = 0; i < 10; i++)
    {
        Mak_b(myqueue, &num);
        printf("-%d", num);
    }
    printf("\n");

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值