初级数据结构--队列

队列

队列:只可以从尾部入队,头部出队,先进先出,一个指针指向链表的头部,一个指针指向链表的尾部。
出队PopFront,入队PushRear.

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

队列的创建,初始化

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

typedef int Dat;

typedef struct QueNode
{
	struct QueNode* next;
	Dat data;
}Qn;

typedef struct QueList
{
	Qn* front;
	Qn* rear;
}QL;

初始化

void QueInit(QL* pq)
{
	assert(pq);
	pq->front = pq->rear = NULL;
}

队列的入队,出队

void QuePush(QL* pq, Dat x)
{
	assert(pq);
	Qn* node = (Qn*)malloc(sizeof(Qn));
	if (node == NULL)
	{
		printf("malloc failed\n");
		exit(-1);
	}
	node->data = x;
	node->next = NULL;
	//一个节点,多个节点
	if (pq->rear == NULL)
	{
		pq->rear = pq->front = node;
	}
	else
	{
		pq->rear->next = node;
		pq->rear = node;
	}
}

出队

void QuePop(QL* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	if (pq->front->next == NULL)
	{
		free(pq->front);
		//他俩指向唯一的一个节点
		pq->front = pq->rear = NULL;
	 }
	else
	{
		Qn* nex = pq->front->next;
		free(pq->front);
		pq->front = nex;
	}
}

队列尾部元素,队列头部元素,队列元素个数

Dat QueRear(QL* pq)
{
	assert(pq);
	检测是否是空队列
	assert(!QueueEmpty(pq));
	return pq->rear->data;
}

队头
Dat QueFront(QL* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->front->data;
}

元素个数
int QueSize(QL* pq)
{
	assert(pq);
	int n = 0;
	 如果频繁调用这个接口函数,
	可以在Queue中给一个size记录数据个数
	Qn* cur = pq->front;
	while (cur)
	{
		++n;
		cur = cur->next;
	}
	return n;
}

队列是否为空,销毁队列

在这里插入图片描述

bool QueueEmpty(QL* pq)
{
	assert(pq);
	return pq->front == NULL && pq->rear == NULL;
}

销毁

void QueDestory(QL* pq)
{
	assert(pq);
	Qn* cur = pq->front;
	while (cur)
	{
		Qn* nex = cur->next;
		free(cur);
		cur = nex;
	}
	pq->front = pq->rear = NULL;
}

队列的测试用例

队列不为空,则一直出队头元素

	while (!QueueEmpty(&qu))
	{
		printf("%d ", QueFront(&qu));
		QuePop(&qu);
	}
	printf("\n");

	printf("队列是否为空:%d\n", QueueEmpty(&qu));
	printf("队列中的有效元素个数:%d\n", QueSize(&qu));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值