#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;
}
}