循环队列(C语言数组实现-纯代码+部分注释)

本文介绍了如何在C语言中使用结构体和函数实现一个循环队列,包括队列的初始化、元素的入队和出队操作,以及队列状态的检查。测试代码展示了队列功能的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件部分

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct queue
{
	int front;
	int tail;
	int* a;//数组
	int k;//存储元素个数
}queue;
queue* cycleQueueInit(int k);
void enQueue(queue* pq, int value);
bool isEmpty(queue* pq);
bool isFull(queue* pq);
void deQueue(queue* pq);
void printQueue(queue* pq);
int getRear(queue* pq);


接口实现

#include "cycle.h"
queue* cycleQueueInit(int k)
{
	//获得一个队列指针
	//开辟空间
	queue* pq = (queue*)malloc(sizeof(queue));
	//为数组开辟空间
	pq->a = (int*)malloc(sizeof(int)*(k+1));//需要多开辟一个空间来判断队列是否存满
	pq->k = k;//长度
	pq->front = pq->tail = 0;
	return pq;

}
void enQueue(queue* pq,int value)
{
	//先判断是否存满
	assert(!isFull(pq));
	//添加元素
	//尾插
	pq->a[pq->tail] = value;
	pq->tail++;
	pq->tail %= ((pq->k) + 1);//避免下标越界
}
bool isEmpty(queue* pq)
{
	return pq->front == pq->tail;
}
bool isFull(queue* pq)
{
	return ((pq->tail + 1) % pq->k) == pq->front;
}
void deQueue(queue* pq)
{
	assert(!isEmpty(pq));
	pq->front++;
	pq->front %= ((pq->k) + 1);//避免下标越界
}
void printQueue(queue* pq)
{
	int length = (pq->tail - pq->front + pq->k+1) % (pq->k+1);//获取到此时队列中元素的个数
	printf("%d", length);
	printf("\n");
	int index = pq->front;
	for (int i = 0; i < length; i++)
	{
		printf("%d->", pq->a[i]);
		index = (index + 1) % (pq->k + 1);//index可能越界
	}
}
int getRear(queue* pq)
{
	assert(!isEmpty(pq));
	int i = (pq->tail + pq->k) % (pq->k + 1);//如果tail为0情况,即最后一个元素下标为k-1时
	return pq->a[i];
}

测试

#include "cycle.h"

int main()
{
	queue*pq=cycleQueueInit(5);
	enQueue(pq, 1);
	enQueue(pq, 2);
	enQueue(pq, 3);
	enQueue(pq, 4);
 	printQueue(pq);
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

1YC..

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

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

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

打赏作者

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

抵扣说明:

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

余额充值