数据结构:队列

目录

队列的概念和结构

队列的实现

结构定义

初始化

判空

入队列

出队列

返回队头元素

返回队尾元素

返回size

销毁


队列的概念和结构

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出 FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头

队列的实现

队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,牵扯挪动数据覆盖,效率会比较低。

结构定义

cpp 复制代码
typedef int QueueDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QueueDataType data;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

初始化

cpp 复制代码
void QueueInit(Queue* pq)
{
	assert(pq);

	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

判空

删除元素和返回队列元素需要判空。

cpp 复制代码
bool QueueEmpty(Queue* pq)
{
	assert(pq);

	return pq->phead == NULL && pq->ptail == NULL;
}

入队列

cpp 复制代码
void QueuePush(Queue* pq, QueueDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("maoolc fail");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	//无节点
	if (pq->phead == NULL)
	{
		assert(pq->ptail == NULL);
		pq->phead = pq->ptail = newnode;
	}
	//多个节点
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}

出队列

cpp 复制代码
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	//一个节点
	if (pq->phead->next == NULL)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		QNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}

	pq->size--;
}

返回队头元素

cpp 复制代码
QueueDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}

返回队尾元素

cpp 复制代码
QueueDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}

返回size

cpp 复制代码
int Queuesize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

销毁

cpp 复制代码
void QueueDestroy(Queue* pq)
{
	assert(pq);

	QNode* cur = pq->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

总结

队列作为一种常见的数据结构,在计算机科学中有广泛的应用,通常运用于广度优先搜索、任务调度等场景。希望这篇文章可以帮助到你更好的学习和理解队列的知识。

相关推荐
cpp_25011 小时前
P8597 [蓝桥杯 2013 省 B] 翻硬币
数据结构·c++·算法·蓝桥杯·题解
郝学胜-神的一滴1 小时前
Python类型检查之isinstance与type:继承之辨与魔法之道
开发语言·数据结构·python·程序人生
不忘不弃1 小时前
把IP地址转换为字符串
数据结构·tcp/ip·算法
发疯幼稚鬼1 小时前
网络流问题与最小生成树
c语言·网络·数据结构·算法·拓扑学
wen__xvn2 小时前
代码随想录算法训练营DAY3第一章 数组part02
java·数据结构·算法
一起养小猫2 小时前
LeetCode100天Day8-缺失数字与只出现一次的数字
java·数据结构·算法·leetcode
梭七y2 小时前
【力扣hot100题】(115)缺失的第一个正数
数据结构·算法·leetcode
weixin_461769403 小时前
5. 最长回文子串
数据结构·c++·算法·动态规划
散峰而望3 小时前
【算法竞赛】C++入门(三)、C++输入输出初级 -- 习题篇
c语言·开发语言·数据结构·c++·算法·github
不会c嘎嘎3 小时前
数据结构 -- 常见的八大排序算法
数据结构·c++·算法·排序算法·面试题·快速排序