基础数据结构——顺序队列(单向)代码实现C


//单向队列
#include<stdio.h>
#include<stdlib.h>
typedef struct queue
{
	int* elements;
	int capacity;
	int head;
	int rear;
}queue;
void QueueInit(queue* q, int capacity);
void QueueDestroy(queue* q);
void QueuePush(queue* q, int elem);
int QueuePop(queue* q);

void QueueInit(queue* q,int capacity)
{
	q->capacity = capacity;
	q->head = q->rear = 0;
	q->elements = (int*)malloc(sizeof(int) * capacity);
	if (q->elements == NULL)
		exit(EXIT_FAILURE);
}
void QueueDestroy(queue* q)
{
	q->capacity = 0;
	q->head = q->rear = 0;
	if (q->elements)
		free(q->elements);
	q->elements = NULL;
}
void QueuePush(queue* q, int elem)
{
	int* new_elements;
	// 判断是否为满,是则扩容
	if (q->rear == q->capacity)
	{
		q->capacity *= 2;
		new_elements = (int*)realloc(q->elements, sizeof(int) * q->capacity);
		if (new_elements == NULL)
			exit(EXIT_FAILURE);
		q->elements = new_elements;
	}
	q->elements[q->rear++] = elem;
}
int QueuePop(queue* q)
{
	if (q->head == q->rear)
	{
		printf("no elements\n");
		exit(EXIT_FAILURE);
	}
	return q->elements[q->head++];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值