单向链表模板

#pragma once

#include <windows.h>
#include <assert.h>

/************************************************************************/
/* C++实现单向链表模板	情形不同,用不同代码							*/
/************************************************************************/

namespace WinListSpace
{

	template<class T>
	struct NodeInfo
	{
		T tData;
		NodeInfo* pNext;
		NodeInfo()
		{
			ZeroMemory(&tData, sizeof(T));
			pNext = nullptr;
		}
	};

	template<class T>
	class WinList
	{
	private:
		NodeInfo<T>* m_pList;
		INT m_nLen;

	private:
		NodeInfo<T>* Allocate();

	public:
		WinList();
		~WinList();

	public:
		BOOL Insert(CONST T&);
		BOOL Delete(CONST T&);
		BOOL AllClear();
		inline INT GetLen()CONST{
			return m_nLen;
		}

	};

	/************************************************************************/
	/*                                                                      */
	/************************************************************************/

	template<class T>
	NodeInfo<T>* WinListSpace::WinList<T>::Allocate()
	{
		NodeInfo<T>* pTemp = nullptr;
		pTemp = dynamic_cast<NodeInfo<T>*>(new NodeInfo<T>);
#ifndef _USEASSERT_ //如果使用断言的话
		assert(pTemp);
#endif
		if (pTemp)
		{
			ZeroMemory(pTemp, sizeof(NodeInfo<T>));
		}
		return pTemp;
	}

	template<class T>
	WinListSpace::WinList<T>::WinList()
	{
		m_pList = nullptr;
		m_nLen = NULL;
	}

	template<class T>
	WinListSpace::WinList<T>::~WinList()
	{
		AllClear();
	}

	template<class T>
	BOOL WinListSpace::WinList<T>::Insert(CONST T& tData)
	{
		NodeInfo<T>* pNode = nullptr;
		pNode = Allocate();
		if (!pNode)
		{
			return FALSE;
		}
		CopyMemory(&pNode->tData, &tData, sizeof(T));
		pNode->pNext = m_pList;
		m_pList = pNode;
		m_nLen++;
		return TRUE;
	}

	template<class T>
	BOOL WinListSpace::WinList<T>::Delete(CONST T& tData)
	{
		NodeInfo<T>* pNode = m_pList;
		NodeInfo<T>* pLast = pNode;
		if (!m_pList)
		{
			return FALSE;
		}
		if (!memcmp(&pNode->tData, &tData, sizeof(T)))
		{
			m_pList = m_pList->pNext;
		}
		else
		{
			pNode = pNode->pNext;
			while (pNode)
			{
				if (!memcmp(&pNode->tData, &tData, sizeof(T)))
				{
					pLast->pNext = pNode->pNext;
					break;
				}
				pLast = pNode;
				pNode = pNode->pNext;
			}
		}
		if (pNode)
		{
			delete pNode;
			m_nLen--;
			return TRUE;
		}
		return FALSE;
	}

	template<class T>
	BOOL WinListSpace::WinList<T>::AllClear()
	{
		NodeInfo<T>* pNode = nullptr;
		while (m_pList)
		{
			pNode = m_pList->pNext;
			delete m_pList;
			m_pList = pNode;
		}
		m_pList = nullptr;
		m_nLen = NULL;
		return TRUE;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值