数据结构之循环队列(c语言实现)

队列——循环队列

一般队列的顺序存储如图

在这里插入图片描述

这种队列顺序存储和插入元素用头插法的顺序表的顺序存储简直一模一样,不过在顺序表的顺序存储的数组的有值部分的最右边加一个对标记(图中多了一个标记),即可。

循环队列会更加方便入队和出队,不过作为顺序存储,循环队列面临着数组可能会溢出的问题。还是来看看,循环队列的图吧。

在这里插入图片描述

循环队列的抽象数据类型

> init_Queue(&Q);  初始化队列
> 
>  En_Queue(&Q);  入队操作
>  
> print_Queue(Q);  打印队列
> 
> len_Queue(Q);   计算队列的长度
> 
> De_Queue(&Q, &e);   出队操作

代码

#include <stdio.h>

#define MAXSIZE 20
typedef int ElemType;

typedef struct
{
    ElemType data[MAXSIZE];
    int Front;    //This is head pointer
    int Rear;     //This is tail pointer
}SqQueue;

void init_Queue(SqQueue *Q)
{
    Q->Front = 0;
    Q->Rear = 0;
}

void En_Queue(SqQueue *Q)
{
    int e;
    int n;
    if ((Q->Rear + 1) % MAXSIZE == Q->Front)
    {
        printf("Enqueue opertion is failed !\n");
        return;
    }
    printf("Please enter the number of elements to be enqueued: ");
    scanf("%d", &n);
    if (n > MAXSIZE - 1)
    {
        printf("The number is out of range!\n");
        return;
    }

    for(int i = 0; i < n; i++)
    {
        printf("Please enter element to be enqueued: ");
        scanf("%d", &e);
        Q->data[Q->Rear] = e;
        Q->Rear = (Q->Rear + 1) % MAXSIZE;
    }
}

void print_Queue(SqQueue Q)
{
    if (Q.Front == Q.Rear)
    {
        printf("The queue is empty !\n");
        return;
    }

    for (int i = Q.Front; i != Q.Rear;)
    {
        printf(" %d ", Q.data[i]);
        i = (i + 1) % MAXSIZE;
    }
    printf("\n");
}

void De_Queue(SqQueue *Q, ElemType *e)
{
    if (Q->Front == Q->Rear)
    {
        printf("The queue is empty !\n");
        return;
    }

    *e = Q->data[Q->Front];
    Q->Front = (Q->Front + 1) % MAXSIZE;
}

int len_Queue(SqQueue Q)
{
    return (Q.Rear - Q.Front + MAXSIZE) % MAXSIZE;
}

int main()
{
    SqQueue Q;

    //Initialization queue
    init_Queue(&Q);

    //Enqueue opertion of the circular queue
    En_Queue(&Q);

    //Print queue contents
    print_Queue(Q);

    //Calculate the length of the circular queue
    int len = 0;
    len = len_Queue(Q);
    printf("The queue`s length is %d\n", len);

    //Dequeue opertion of the circular queue
    ElemType e;
    De_Queue(&Q, &e);
    printf("The value to be dequeued is %d\n", e);

    print_Queue(Q);

    len = len_Queue(Q);
    printf("The queue`s length is %d\n", len);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值