当前位置:主页 > 软件编程 > C代码 >

C++使用模板实现单链表

时间:2021-03-29 09:42:47 | 栏目:C代码 | 点击:

本文实例为大家分享了用模板实现单链表,供大家参考,具体内容如下

话不多说 直接上代码

#include <iostream>
using namespace std;
 
template<typename E>
class CLink;
 
template<typename T>
class Node
{
 friend class CLink<T>;
 
public:
 /*
 构造函数和析构函数一般不加类型参数
 本类类中除了构造函数和析构函数以外
 其它的地方都要加上类型参数
 */
 Node(T data = 0)
 {
 mdata = data;
 pnext = NULL;
 }
 ~Node(){}
 
private:
 T mdata;
 Node<T>* pnext;
};
 
template<typename T>
class CLink
{
public:
 CLink()
 {
 phead = new Node<T>();
 }
 void InsertHead(T data)
 {
 Node<T>* pNewNode = new Node<T>(data);
 pNewNode->pnext = phead->pnext;
 phead->pnext = pNewNode;
 } 
 
 void InsertTail(T data)
 {
 Node<T>* pNewNode = new Node<T>(data);
 Node<T>* pCur = phead;
 while(pCur->pnext != NULL)
 {
 pCur = pCur->pnext;
 }
 pCur->pnext = pNewNode;
 }
 
 void Show()
 {
 Node<T>* pCur = phead->pnext;
 while (pCur != NULL)
 {
 cout << pCur->mdata << " ";
 pCur = pCur->pnext;
 }
 cout << endl;
 }
 
 ~CLink()
 {
 Node<T>* pCur = phead;
 Node<T>* pNext = phead;
 while (pCur != NULL)
 {
 pNext = pCur->pnext;
 delete pCur;
 pCur = pNext;
 }
 phead = NULL;
 } 
 
private:
 Node<T>* phead;
};
 
int main()
{
 CLink<int> list1;
 CLink<int> list2;
 
 for(int i = 0;i < 10;i++)
 {
 list1.InsertHead(i + 1);
 list2.InsertTail(i * 2);
 }
 cout << "list1:";
 list1.Show();
 
 cout << "list2:";
 list2.Show();
 
 return 0;
}

运行结果:

您可能感兴趣的文章:

相关文章