亲宝软件园·资讯

展开

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

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

话不多说 直接上代码

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

运行结果:

加载全部内容

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