数据结构:队列

目录

队列的概念和结构

队列的实现

结构定义

初始化

判空

入队列

出队列

返回队头元素

返回队尾元素

返回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;
}

总结

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

相关推荐
皓月斯语12 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
春日见13 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
萌动的小火苗13 小时前
嵌入式开发中的栈与队列:任务调度为什么依赖数据结构
数据结构·c++·单片机·嵌入式硬件
叩码以求索13 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana214 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
星恒随风14 小时前
C++ STL 栈详解:stack 的使用、经典题目与简单模拟实现
开发语言·数据结构·c++·笔记·学习
txzrxz14 小时前
单调队列讲解
数据结构·c++·算法·单调队列
Keven_1115 小时前
算法札记:树状数组的用途
数据结构·算法
cpp_250115 小时前
P1540 [NOIP 2010 提高组] 机器翻译
数据结构·c++·算法·队列·noip·洛谷题解
星恒随风18 小时前
C++ STL 详解:list 的使用、迭代器失效、模拟实现与 vector 对比
开发语言·数据结构·c++·笔记·学习·list