亲宝软件园·资讯

展开

C++单链表 C++使用模板实现单链表(类外实现)

牧童遥指杏花村丫 人气:0

这一篇可以和上一篇 点击打开链接 模板实现单链表进行对比 

看类外实现和类内实现的区别

代码:

#include <iostream>
using namespace std;
 
template<typename T>
class CLink
{
public:
 class Node;
 CLink();//无参的构造函数
 void InsertHead(T data);//头插
 void InsertTail(T data);//尾插
 void Show();//打印
 ~CLink();//析构
 Node* Find(T val);//查找
 
private:
 class Node
 {
 public:
 Node(T data = 0);
 ~Node(){}
 public:
 T mdata;
 Node* pnext;
 };
 Node* phead;
};
 
//类外实现无参的构造
template<typename T>
CLink<T>::CLink()
{
 phead = new Node();
} 
 
//类外实现头插
template<typename T>
void CLink<T>::InsertHead(T data)
{
 Node* pNewNode = new Node(data);
 pNewNode->pnext = phead->pnext;
 phead->pnext = pNewNode;
}
 
 
//类外实现尾插
template<typename T>
void CLink<T>::InsertTail(T data)
{
 Node* pNewNode = new Node(data);
 Node* pCur = phead;
 while(pCur->pnext != NULL)
 {
 pCur = pCur->pnext;
 }
 pCur->pnext = pNewNode;
}
 
 
//类外实现打印函数
template<typename T>
void CLink<T>::Show()
{
 Node* pCur = phead->pnext;
 while (pCur != NULL)
 {
 cout << pCur->mdata << " ";
 pCur = pCur->pnext;
 }
 cout << endl;
}
 
//类外实现析构函数
template<typename T>
CLink<T>::~CLink()
{
 Node* pCur = phead;
 Node* pNext = phead;
 while (pCur != NULL)
 {
 pNext = pCur->pnext;
 delete pCur;
 pCur = pNext;
 }
 phead = NULL;
}
 
//类外实现结点的构造
template<typename T>
CLink<T>::Node::Node(T data)
{
 mdata = data;
 pnext = NULL;
}
 
//类外实现查找函数
template<typename T>
typename CLink<T>::Node* CLink<T>::Find(T val)
{
 Node* pCur = phead->pnext;
 while (pCur != NULL)
 {
 if (pCur->mdata == val)
 {
 return pCur;
 }
 pCur = pCur->pnext;
 }
 return pCur;
}
 
int main()
{
 CLink<int> link1;
 CLink<int> link2;
 
 for(int i = 0;i < 10;i++)
 {
 link1.InsertHead(i + 1);
 link2.InsertTail(i * 2);
 }
 cout << "link1:";
 link1.Show();
 
 cout << "link2:";
 link2.Show();
 
 link1.Find(10);
 
 return 0;
}

运行结果:

加载全部内容

相关教程
猜你喜欢
用户评论