本文實例為大家分享了C++使用模板實現單鏈表的具體代碼,供大家參考,具體內容如下
這一篇可以和上一篇 點擊打開鏈接 模板實現單鏈表進行對比
看類外實現和類內實現的區別
代碼:
#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;}
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答