基于链表实现的队列(模板)

本文介绍了一种基于C++模板的循环单链表队列(CSLQueue)的实现细节,包括队列的基本操作如入队(EnQueue)、出队(DeQueue)、清空(Clear)及打印(Print)。通过具体代码示例展示了队列遵循先进先出的原则,并提供了完整的运行实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列:先进先出

代码实现:

#pragma  once

#include <iostream>
template <typename T>
class CSLQueue
{
	typedef struct ST_NODE {
		T* pData;
		ST_NODE* pNext;
	}ST_SL_NODE;
public:
	CSLQueue();
	~CSLQueue();

	bool EnQueue(T* pData);

	//need to free memory in caller
	T* DeQueue();

	void Clear();

	void Print();
private:
	ST_SL_NODE* m_pHead;
	ST_SL_NODE* m_pTail;
};

template <typename T>
CSLQueue<T>::CSLQueue():m_pHead(nullptr), m_pTail(nullptr)
{
}

template <typename T>
CSLQueue<T>::~CSLQueue()
{
	Clear();
}

template <typename T>
bool CSLQueue<T>::EnQueue(T* pData)
{
	if (pData == nullptr)
	{
		return false;
	}

	ST_SL_NODE* pNode = new ST_SL_NODE{nullptr, nullptr};
	pNode->pData = new T;
	*(pNode->pData) = *pData;

	if (m_pTail)
	{
		m_pTail->pNext = pNode;
		m_pTail = pNode;
	}
	else
	{
		m_pHead = m_pTail = pNode;
	}

	return true;
}

template <typename T>
T* CSLQueue<T>::DeQueue()
{
	T* pData = nullptr;

	if (m_pHead)
	{
		ST_SL_NODE* pNode = m_pHead;
		m_pHead = m_pHead->pNext;
		if (m_pHead == nullptr)
		{
			m_pTail = m_pHead;
		}

		pData = pNode->pData;
		delete pNode;
		pNode = nullptr;

	}

	return pData;
}


template <typename T>
void CSLQueue<T>::Clear()
{
	
	while (m_pHead)
	{
		ST_SL_NODE* pNode = m_pHead;
		m_pHead = m_pHead->pNext;

		delete pNode->pData;
		delete pNode;
	}
	m_pTail = m_pHead;

}

template <typename T>
void CSLQueue<T>::Print()
{
	using namespace std;
	ST_SL_NODE* pNode = m_pHead;
	if (pNode == nullptr)
	{
		cout << "This is an empty queue!" << endl;
		return;
	}
	while (pNode)
	{
		cout << *(pNode->pData) << endl;
		pNode = pNode->pNext;
	}
}

使用:

#include <iostream>
#include "queue.h"
using namespace std;

int main(int argc, char* argv[])
{
	CSLQueue<int> oSLQueue;
	cout << "*******Should print empty queue*******" <<endl;
	oSLQueue.Print();

	int* pNumList = new int[20];
	for (int i = 0; i < 20; i++)
	{
		pNumList[i] = i;
	}

	cout << "*******Insert queue*******" << endl;
	for (int i = 0; i < 20; i++)
	{
		oSLQueue.EnQueue(&pNumList[i]);
	}
	oSLQueue.Print();

	cout << "*******Delete queue*******" << endl;
	for (int i = 0; i < 20; i++)
	{
		int * pData = oSLQueue.DeQueue();
		cout << "Delete "<< *pData << endl;
		delete pData;
	}
	oSLQueue.Print();

	return 0;
}

输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值