本文实例为大家分享了用模板实现单链表,供大家参考,具体内容如下
话不多说 直接上代码
#includeusing namespace std; template class CLink; template class Node { friend class CLink ; public: /* 构造函数和析构函数一般不加类型参数 本类类中除了构造函数和析构函数以外 其它的地方都要加上类型参数 */ Node(T data = 0) { mdata = data; pnext = NULL; } ~Node(){} private: T mdata; Node * pnext; }; template class CLink { public: CLink() { phead = new Node (); } void InsertHead(T data) { Node * pNewNode = new Node (data); pNewNode->pnext = phead->pnext; phead->pnext = pNewNode; } void InsertTail(T data) { Node * pNewNode = new Node (data); Node * pCur = phead; while(pCur->pnext != NULL) { pCur = pCur->pnext; } pCur->pnext = pNewNode; } void Show() { Node * pCur = phead->pnext; while (pCur != NULL) { cout < mdata <<" "; pCur = pCur->pnext; } cout < * pCur = phead; Node * pNext = phead; while (pCur != NULL) { pNext = pCur->pnext; delete pCur; pCur = pNext; } phead = NULL; } private: Node * phead; }; int main() { CLink list1; CLink 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; }
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。