c语言写的环形队列

        以下是一个简单的环形队列的实现示例,包括初始化、入队、出队、查询当前元素个数、队列长度和队列元素可视化。

        这里使用了静态数组来实现队列的存储,适合于固定大小的队列。

#include <stdio.h>
#define MAX_QUEUE_SIZE 10  // 定义队列的最大容量
typedef struct {    
int data[MAX_QUEUE_SIZE];  // 队列的数据数组    
int front;  // 队头指针,指向队首元素的位置    
int rear;   // 队尾指针,指向队尾元素的下一个位置    
int count;  // 队列当前元素个数
}CircularQueue;
// 初始化队列
void initQueue(CircularQueue *queue) {    
queue->front = 0;    
queue->rear = 0;    
queue->count = 0;
}
// 入队操作
void enqueue(CircularQueue *queue, int value) {    
if (queue->count >= MAX_QUEUE_SIZE) {        
printf("队列已满,无法入队!\n");        
return;    
}    
queue->data[queue->rear] = value;    
queue->rear = (queue->rear + 1) % MAX_QUEUE_SIZE;  // 更新rear指针,注意取模操作    
queue->count++;
}
// 出队操作
int dequeue(CircularQueue *queue) {    
if (queue->count <= 0) {        
printf("队列为空,无法出队!\n");        
return -1;  // 返回一个特殊值表示出错    
}    
int value = queue->data[queue->front];    
queue->front = (queue->front + 1) % MAX_QUEUE_SIZE;  // 更新front指针,注意取模操作    
queue->count--;    
return value;
}
// 查询当前队列元素个数
int queueCount(CircularQueue *queue) {    
return queue->count;
}
// 查询队列长度(最大容量)
int queueLength() {    
return MAX_QUEUE_SIZE;
}
// 打印队列元素(可视化)
void printQueue(CircularQueue *queue) {    
printf("队列中的元素为:");    
int i = queue->front;    
int cnt = 0;    
while (cnt < queue->count) {        
printf("%d ", queue->data[i]);        
i = (i + 1) % MAX_QUEUE_SIZE;        
cnt++;    
}    
printf("\n");
}
// 示例程序int main() {    
CircularQueue queue;    
initQueue(&queue);
    enqueue(&queue, 1);    
enqueue(&queue, 2);    
enqueue(&queue, 3);    
printQueue(&queue);  // 输出:队列中的元素为:1 2 3
    dequeue(&queue);    
printQueue(&queue);  // 输出:队列中的元素为:2 3
    printf("当前队列元素个数:%d\n", queueCount(&queue));  // 输出:当前队列元素个数:2    
printf("队列长度:%d\n", queueLength());  // 输出:队列长度:10
    return 0;
}

==============================================

可以正常运行:

队列中的元素为:1 2 3 队列中的元素为:2 3 当前队列元素个数:2队列长度:10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值