由于工作中经常用到链表,所以自己封装了个简单的链表模板类。以便使用
/*
* 链表模板
*/
#pragma once
#define NULL 0
template <class T> class PtrList
{
public:
PtrList() { pFirst = 0; }
PtrList(PtrList &p) { pFirst = p.pFirst; }
void AddNode (T &t); // 增加结点
void RemoveNode (T &t); // 移除结点
void RemoveAll (); // 移除所有结点
T * FindNode (T &t); // 查找结点
T * GetNode(); // 遍历结点
~PtrList();
protected:
struct Node{
Node *pNext;
T *Pt;
};
Node * pFirst;
};
template <class T>
void PtrList<T>::AddNode(T &t)
{
Node *temp = new Node;
temp->Pt = &t;
temp->pNext = pFirst;
pFirst = temp;
}
template <class T>
T * PtrList<T>::FindNode(T &t)
{
for (Node *p = pFirst; p; p = p->pNext)
{
if ( *(p->Pt) == t)
return p->Pt;
}
return NULL;
}
/*
* 调用者可通过循环调用此函数以遍历所有结点。
*
*/
template<class T>
T * PtrList<T>::GetNode()
{
if (pFirst == NULL)
return NULL;
Node *p = pFirst;
pFirst = pFirst->pNext;
return p->Pt;
}
template <class T>
void PtrList<T>::RemoveNode(T &t)
{
Node *q = 0;
if ( *(pFirst->Pt) == t)
{
q = pFirst;
pFirst = pFirst->pNext;
}
else
{
for (Node *p = pFirst; p->pNext; p = p->pNext)
if ( *(p->pNext->Pt) == t)
{
q = p->pNext;
p->pNext = q->pNext;
break;
}
}
if (q)
{
delete q;
q = 0;
}
}
template <class T>
void PtrList<T>::RemoveAll()
{
Node *p = 0;
while (p = pFirst)
{
pFirst = pFirst->pNext;
delete p;
p = 0;
}
}
template <class T>
PtrList<T>::~PtrList()
{
Node *p = 0;
while (p = pFirst)
{
pFirst = pFirst->pNext;
delete p;
p = 0;
}
}
使用方法:
PtrList <int> List, List1; // 模板实例化
int i = 34, j = 35, k = 36;
List.AddNode(i); // 增加结点
List.AddNode(j);
List.AddNode(k);
List.RemoveNode(j); // 移除结点
List1 = List; // 此句为了后面的遍历所使用
while (1)
{
int *dd = List1.GetNode(); // 通过while遍历所有结点
if (dd == 0)
break;
}