队列的基本操作

队列的初始化

void QueueInit(Queue* pq)
{
	if (pq == NULL)
	{
		return;
	}
	pq->head = pq->tail = NULL;
}

队列的销毁

void QueueDestroy(Queue* pq)
{
	QNode* node = pq->head;
	while (node!= pq->tail)
	{
		QNode* cur = node->next;
		free(node);
		node = cur;
	}
	pq->head = NULL;
	pq->tail = NULL;
	
}

入队

void QueuePush(Queue* pq, QDataType x)
{
	if (pq == NULL)
	{
		return;
	}
	QueueNode* newNode = new QueueNode;
	newNode->next = NULL;
	newNode->data = x;
	if (pq->tail == NULL)
	{
		pq->head = pq->tail = newNode;
	}
	else
	{
		pq->tail->next = newNode;
		pq->tail = newNode;
	}

}


出队

void QueuePop(Queue* pq)
{
	if (pq == NULL)
	{
		return;
	}
	if (pq->tail == NULL)
	{
		return;
	}
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = NULL;
		pq->tail = NULL;
		return;
	}
	QNode* newNode = pq->head;
	pq->head = newNode->next;
	free(newNode);
	newNode = NULL;
	 
}

取得队头元素

QDataType QueueFront(Queue* pq)
{
	if (pq == NULL)
	{
		return NULL;
	}
	if (pq->head != NULL)
	{
		return pq->head->data;
	}
	return NULL;
}

取得队尾元素

QDataType QueueBack(Queue* pq)
{
	if (pq == NULL)
	{
		return NULL;
	}
	if (pq->tail != NULL)
	{
		return pq->tail->data;
	}
	return NULL;
}

队列大小

int QueueSize(Queue* pq)
{
	int count = 0;
	if (pq == NULL)
	{
		return NULL;
	}
	QNode* newNode = pq->head;
	while (newNode)
	{
		newNode = newNode->next;
		count++;
	}
	return count;
}

判断队列是否为空

bool QueueEmpty(Queue* pq)
{
	if (pq == NULL)
	{
		return true;
	}
	return pq->tail == NULL;
}

测试

void test()
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q,1);
	QueuePush(&q, 3);
	QueuePush(&q, 5);
	QueuePush(&q, 7);
	QueuePush(&q, 8);
	QueuePush(&q, 11);
	int size = QueueSize(&q);
	cout << "队列的大小:" << size << endl;
	while (!QueueEmpty(&q))
	{
		cout<< QueueFront(&q)<< " ";
		QueuePop(&q);
	}
	QueueDestroy(&q);

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值