队列

队列的概念及结构

队列和栈略有不同,队列是先进后出的一种数据结构,通常使用链表来表示,当然有一种特殊的循环队列使用顺序表来进行表示的。
队列只允许从后进入,从前弹出,就像我们生活中排队一样,下面来看下队列的结构模型:
在这里插入图片描述
如上图,队列是只有队头才能删除元素(出队),队尾才能插入元素(入队),由此可以得出数据结构为:

typedef int QDataType;
//定义结点的结构体
typedef struct QNode
{
	QDataType val; 
	strcut QNode* next;
}QNode;
//定义队列的结构体
typedef struct Queue
{
	QNode* head;  //队头指针
	QNode* tail;   //队尾指针
}Queue;

队列代码实现

初始化

void QueueInit(Queue* Q)
{
	Q->head = Q->tail = NULL;
}

创建节点

QNode* CreateQNode(QDataType data)
{
	QNode* node = (QNode*)malloc(sizeof(QNode));

	node->next = NULL;
	node->data = data;

	return node;
}

入队

void QueuePush(Queue* Q, QDataType data)
{
	QNode* node = CreateQNode(data);

	if (!Q->head)
	{
		Q->head = Q->tail = node;
	}

	Q->tail->next = node;
	Q->tail = node;
}

出队

void QueuePop(Queue* Q)
{
	if (!Q->head)
	{
		return;
	}

	QNode* next = Q->head->next;
	free(Q->head);
	Q->head = next;

	if (!Q->head)
	{
		Q->tail = NULL;
	}
}

获取队首元素

QDataType QueueHeadElement(Queue* Q)
{
	return Q->head->data;
}

获取队尾元素

QDataType QueueTailElement(Queue* Q)
{
	return Q->tail->data;
}

队列元素个数

int QueueSize(Queue* Q)
{
	int count = 0;
	QNode* cur = Q->head;

	while (cur)
	{
		cur = cur->next;
		count++;
	}

	return count;
}

判空

int QueueEmpty(Queue* Q)
{
	if (!Q->head)
	{
		return 1;
	}

	return 0;
}

销毁

void QueueDestroy(Queue* Q)
{
	QNode* next;

	while (Q->head)
	{
		next = Q->head->next;
		free(Q->head);
		Q->head = next;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值