循环队列及C语言实现<一>

  循环队列是为了充分利用内存,进行数据操作的一种基本算法。具体实现方式可划分为:链式队列和静态队列,这里所谓的静态是指在一片连续的内存区域进行数据操作。本文只讲述静态队列,也是最简单的实现方式,链式队列以及链表的实现内容请参见我的其它博文。以下静态循环队列简称为循环队列。
  
一、循环队列的特点及要素
<1> 先进先出(FIFO);
<2> 首尾元素 front 和 rear 的数值;
<3> 队列操作: 队列初始化、销毁队列、遍历队列、队列满、队列空、入队列,出队列。
<4> 队列满判断的两种方式:因为需要区分与队列空时 front 与 rear 的位置关系。
方式一:front == rear 并且 flag_full = true;
方式二:front= (rear + 1) % size;

二、具体实现及输出结果见下面程序,因为较为简单,不作注解了。有疑问可以 send comments to me。

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

typedef struct queue{
    char *buf;
    int front;
    int rear;
    int size;
} Queue, *pQueue;

void Init_Queue(Queue *q, int maxsize)
{
    q->buf = (char *)malloc(sizeof(char) * maxsize);
    if (q->buf == NULL) {
        perror("malloc error: ");
        exit(1);
    }
    q->front = 0;
    q->rear = 0;
    q->size = maxsize;
}

void Destroy_Queue(Queue *q)
{
    free(q->buf);
}

void Traverse_Queue(Queue *q)
{
    int i = q->front;

    while (i % q->size != q->rear) {
        printf("buf[%d]: %d\n", i, q->buf[i]);
        i++;
    }
}

bool Queue_Empty(Queue *q)
{
    return (q->front == q->rear);
}

bool Queue_Full(Queue *q)
{
    return (q->front == ((q->rear + 1) % q->size));
}

bool EnQueue(Queue *q, char val)
{
    if (!Queue_Full(q)) {
        *(q->buf + q->rear) = val;
        q->rear = (q->rear + 1) % q->size;
        return true;
    }
    printf("Queue Full!\n");
    return false;
}

bool DeQueue(Queue *q, char *val)
{
    if(!Queue_Empty(q)) {
        *val = *(q->buf + q->front);
        q->front = (q->front + 1) % q->size;
        return true;
    } 
    printf("Queue Empty!\n");
    return false;
}

void main()
{
    Queue q;
    char a;

    Init_Queue(&q, 6);

    printf("Input queue elements: \n");
    while(!Queue_Full(&q)) {
        scanf("%d", &a);
        EnQueue(&q, a);
    }

    printf("Traverse queue elements: \n");
    Traverse_Queue(&q);

    printf("Delete queue elements: \n");
    while(!Queue_Empty(&q)) {
        DeQueue(&q, &a);
        printf("%d\n", a);
    }
    Destroy_Queue(&q);
}

程序运行结果:

这里写图片描述
关于循环队列主题的系列文章,可移步至以下链接:
1. 《循环队列及C语言实现<一>》
2. 《循环队列及C语言实现<二>》
3. 《循环队列及C语言实现<三>》

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值