《数据结构-C语言实现队列(Queue)》

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

#define MAX_SIZE 100 // 队列的最大容量

typedef struct {
    int items[MAX_SIZE];
    int front; // 队头元素的下标
    int rear;  // 队尾元素的下标
} Queue;

// 初始化队列
void init(Queue *q) {
    q->front = -1;
    q->rear = -1;
}

// 判断队列是否为空
int is_empty(Queue *q) {
    return q->front == -1;
}

// 判断队列是否已满
int is_full(Queue *q) {
    return q->rear == MAX_SIZE - 1;
}

// 入队
void enqueue(Queue *q, int item) {
    if (is_full(q)) {
        printf("Error: queue is full\n");
        return;
    }

    if (q->front == -1) {
        q->front = 0;
    }

    q->rear++;
    q->items[q->rear] = item;
}

// 出队
int dequeue(Queue *q) {
    if (is_empty(q)) {
        printf("Error: queue is empty\n");
        return -1; // 返回-1表示出队失败
    }

    int item = q->items[q->front];
    q->front++;

    if (q->front > q->rear) {
        q->front = q->rear = -1;
    }

    return item;
}

// 获取队头元素
int peek(Queue *q) {
    if (is_empty(q)) {
        printf("Error: queue is empty\n");
        return -1; // 返回-1表示获取队头元素失败
    }

    return q->items[q->front];
}

// 获取队列的大小
int size(Queue *q) {
    if (is_empty(q)) {
        return 0;
    }

    return q->rear - q->front + 1;
}

// 测试队列的实现
int main() {
    Queue q;
    init(&q);

    enqueue(&q, 1);
    enqueue(&q, 2);
    enqueue(&q, 3);

    printf("%d\n", peek(&q)); // 输出 1

    dequeue(&q);

    printf("%d\n", peek(&q)); // 输出 2

    printf("%d\n", size(&q)); // 输出 2

    printf("%d\n", is_empty(&q)); // 输出 0 (false)

    return 0;
}

这个Queue结构体有以下几个方法:

  • init(Queue *q): 初始化一个空队列。
  • is_empty(Queue *q): 检查队列是否为空,如果是返回1,否则返回0。
  • is_full(Queue *q): 检查队列是否已满,如果是返回1,否则返回0。
  • enqueue(Queue *q, int item): 将一个元素添加到队列的末尾。
  • dequeue(Queue *q): 从队列的开头弹出一个元素,并将其从队列中删除。
  • peek(Queue *q): 返回队头的元素,但不删除它。
  • size(Queue *q): 返回队列中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Like_Bamboo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值