循环队列操作集合

#include <stdio.h>
#include <stdlib.h>
#define N 6

typedef struct
{
    int data[N];
    int tail;//队尾:放数据端
    int head;//队头:取数据端
}LoopQueue;

// 创建空队列
LoopQueue* initQueue()
{
    LoopQueue* p = (LoopQueue*)malloc(sizeof(LoopQueue));
    if (p == NULL)
    {
        perror("init malloc err\n");
        return NULL;
    }
    
    // 初始化
    p->head = 0;//队头
    p->tail = 0;//队尾:当其加1=N时,此时认为队列已满
    return p;
}
// 判空
int isNullQueue(LoopQueue* p)
{
    return p->head == p->tail;
}

// 判满
int isFullQueue(LoopQueue* p)
{
    return (p->tail +1) % N == 0;
}

// 入列
void inQueue(LoopQueue* p, int data)
{
    // 判满
    if (isFullQueue(p))//判断队列是否满,
    {
        printf("队列满!\n");
        return;
    }
    //没满数据存入列
    p->data[p->tail] = data;
    // 队尾向后移动
    p->tail = (p->tail +1) % N;
}

// 出列
void outQueue(LoopQueue* p)
{
    // 容错判断
    if (isNullQueue(p))
    {
        printf("空队!\n");
        return;
    }
    // 保存出列数据
    int temp = p->data[p->head];
    // 队头向后移动
    p->head = (p->head + 1) % N;
    printf("出列:%d\n", temp);
}

// 清空队列
void noneQueue(LoopQueue* p)
{
    while(!isNullQueue(p))
    {
        outQueue(p);
    }
    
}

// 队列长度:存在tail<head的情况
void queueLength(LoopQueue* p)
{
    if (p->head < p->tail)
    {
        printf("队长:%d\n", p->tail - p->head);
    }
    else
    {
         printf("队长:%d\n", p->tail - p->head + N);
    }
    
    
}

// 遍历:存在tail<head的情况
void printQueue(LoopQueue* p)
{
    for (int i = p->head; i < p->tail; i++)//这里不能等于tail,因为p->data[5]不储存数,所以不打印
    {
        printf("%d-", p->data[i]);
    }
    printf("NULL\n");
}

int main(int argc, char const *argv[])
{
    LoopQueue* p = initQueue();
    inQueue(p, 1);
    inQueue(p, 2);
    inQueue(p, 3);
    inQueue(p, 4);
    inQueue(p, 5);
    queueLength(p);
    // inQueue(p, 6);
    printQueue(p);

    outQueue(p);
    queueLength(p);
    printQueue(p);

    noneQueue(p);
    printQueue(p);
    return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值