数据结构—队列

1.队列的概念及结构

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出性质。
入队列:进行插入操作的一端称为队尾 。
出队列:进行删除操作的一端称为队头。
在这里插入图片描述

2.队列的实现

队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
在这里插入图片描述
我们会发现他们入队的效果其实一样,但是出队就不一样,数组需要将后面的每一个元素都往前挪动,而链表就是改变头结点的位置就可以了。

2.1初始化队列

初始化队列就是将队头队尾置空就可以了。

//链式结构:表示队列
typedef int QDataType;
typedef struct QListNode
{
	struct QListNode* next;
	QDataType data;
};
//队列的结构
typedef struct Queue
{
	struct Queue* head;
	struct Queue* tail;
}Queue;
//初始化队列
void QueueInit(Queue* pq)
{
	assert(pq);

	pq->head = NULL;
	pq->tail = NULL;
}

2.2队尾入队列

在这里插入图片描述

//队尾入队列
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	assert(newnode);
	newnode->data = x;
	newnode->next = NULL;

	if (pq->tail == NULL)
	{
		assert(pq->head == NULL);
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}

在这里插入图片描述

2.3队头出队列

在这里插入图片描述

//队头出队列
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->head && pq->tail);
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QNode* next = pq->head->next;
		free(pq->head);
		pq->head = next;
	}
}

2.4获取队列头部元素

获取队列头部元素就是将头部元素的值给返回回来:
在这里插入图片描述

//获取队列头部元素
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->head);
	return pq->head->data;
}

2.5获取队列尾部元素

获取队列尾部元素就是将尾部元素的值给返回回来:
在这里插入图片描述

//获取队列头部元素
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->tail);

	return pq->tail->data;
}

2.6获取队列中有效元素个数

//获取队列中有效元素个数
int QueueSize(Queue* pq)
{
	assert(pq);
	int count = 0;
	QNode* cur = pq->head;
	while (cur)
	{
		cur = cur->next;
		count++;
	}
	return count;
}

2.7判断队列是否为空

//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->head == NULL;
}

2.9队列的销毁

//队列的销毁
void QueueDestory(Queue* pq)
{
	assert(pq);
	assert(pq->head);
	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

以上如有错误,请批评指正!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值