问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

C语言实现循环队列

创作时间:
作者:
@小白创作中心

C语言实现循环队列

引用
CSDN
1.
https://m.blog.csdn.net/weixin_41542504/article/details/138303063

循环队列是一种特殊的队列数据结构,其特点是队尾和队头可以相互覆盖,从而实现存储空间的循环利用。本文将通过C语言代码实现一个简单的循环队列,并演示其基本操作。

循环队列的C语言实现

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

#define MAX_SIZE 6
typedef unsigned char uint8;
typedef unsigned int  uint32;
typedef unsigned short WORD;

int queue[MAX_SIZE];
int head = 0;
int tail = 0;

// 入队操作
void enqueue(int element) {
    if ((tail + 1) % MAX_SIZE == head) {
        queue[tail] = element;
        tail = (tail + 1) % MAX_SIZE;
        head = (head + 1) % MAX_SIZE;
    }
    else
    {
        queue[tail] = element;
        tail = (tail + 1) % MAX_SIZE;
    }
    return;
}

// 出队操作
int dequeue() {
    if (head == tail) {
        printf("队列为空\n");
        return -1;
    }
    int result = queue[head];
    head = (head + 1) % MAX_SIZE;
    return result;
}

// 打印队列
void printQueue() {
   int num = 0;
   int y = head;
    num = ((tail-head)+MAX_SIZE)%MAX_SIZE;
    if(num == 0x00)
    {
        printf("队列为空\n");
    }
    else
    {
        for(int i = 0; i< num; i++)
        {
            printf("%d ",queue[y]);
            y = (y + 1) % MAX_SIZE;
        }
        printf("\n");
    }
    
}

int main() {
    printQueue(); 
    // 入队操作
    enqueue(1);
    enqueue(2);
    enqueue(3);
    enqueue(4);
    enqueue(5);
    printQueue(); // 输出: 1 2 3 4 5

    // 出队操作
  printf("出队元素: %d\n", dequeue());
  printf("出队元素: %d\n", dequeue());
  printQueue(); // 输出: 3 4 5

    // 再次入队
    enqueue(6);
    enqueue(7);
    enqueue(8);
    enqueue(9);
    printQueue(); // 输出: 5 6 7 8 9 

    return 0;
}  

验证结果

以下是代码运行的验证结果:

通过上述代码和运行结果,我们可以看到循环队列的基本操作(入队、出队)以及队列元素的打印功能都得到了正确实现。循环队列通过取模运算实现了队尾和队头的循环覆盖,从而有效地利用了存储空间。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号