数据结构——队列

一.队列的基本概念与定义
1.队列(Queue)与栈一样,是一种线性存储结构,它具有如下特点:

(1)队列中的数据元素遵循“先进先出”(First In First Out)的原则,简称FIFO结构;

(2)在队尾添加元素,在队头删除元素。

2.队列的相关概念
(1)队头与队尾: 允许元素插入的一端称为队尾,允许元素删除的一端称为队头;

(2)入队:元素从队尾插入;

(3)出队:元素从队头删除。
3.循环队列
(1).以链表为结构的循环队列
(2).以数组的循环队列

如何判断空队列是已满的
栈空:是队首标志==队尾标志的时候
栈满:队尾+1=队首

见具体OJ题目
在这里插入图片描述

二.队列的代码定义

队列的链式存储结构

typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QueueNode;
typedef struct Queue
{
	QueueNode* head;//队头结点
	QueueNode* tail;//队尾结点
}Queue;

三.队列常用操作的代码实现

1.队列初始化

void QueueInit(Queue* pq)
{
	assert(pq);

	//初始化队列
	pq->head = NULL;
	pq->tail = NULL;
}

2.队列销毁

void QueueDestroy(Queue* pq)
{
	assert(pq);
	QueueNode* cur = pq->head;

	while (cur!=NULL)
	{
		QueueNode* next = cur->next;
		//迭代销毁
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

3.元素入列

void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	//新建一个队列结点
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	//给结点初始化
	newnode->data = x;
	newnode->next = NULL;

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

4.元素出列

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	//迭代队列的头结点
	QueueNode* next = pq->head->next;
	free(pq->head);
	pq->head = next;

	//若把队列中的所有元素全部出列了,tail就是个野指针
	if (pq->head == NULL)
	{
		pq->tail = NULL;
	}
}

5.查询队头元素值

QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));


	return pq->head->data;
}

6.查询队尾元素值

QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->tail->data;
}

7.查询队列元素的个数

int QueueSize(Queue* pq)
{
	assert(pq);
	//返回队列的长度
	int n = 0;
	QueueNode* cur = pq->head;
	while (cur)
	{
		cur = cur->next;
		n++;
	}
	return n;
}

8.判断队列是否为空

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值