(1)单向链表
//单向链表 #include<iostream.h> #include<iomanip.h> class CNode //节点类 { public: CNode *m_pNext; int m_Data; CNode():m_pNext(NULL){} }; class CList //链表类 { public: CList() { m_pHeader=NULL; m_NodeSum=0; } CNode* MoveTrail(CNode *pNode)//移动到尾节点 { CNode *pTmp=m_pHeader; for(int i=1;i<m_NodeSum;i++) { pTmp=pTmp->m_pNext; } return pTmp; } void AddNode(CNode *pNode)//添加节点 { if(0==m_NodeSum) { m_pHeader=pNode; } else { CNode *pTrail=MoveTrail(pNode); pTrail->m_pNext=pNode; } m_NodeSum++; } void PassList()//遍历链表 { if(m_NodeSum>0) { CNode *pTmp=m_pHeader; cout<<setw(5)<<pTmp->m_Data; for(int i=1;i<m_NodeSum;i++) { pTmp=pTmp->m_pNext; cout<<setw(5)<<pTmp->m_Data; } } cout<<endl; } ~CList()//定义链表的析构函数 { if(m_NodeSum>0) { CNode *pDelete=m_pHeader; CNode *pTmp=NULL; for(int i=1;i<m_NodeSum;i++) { pTmp=pDelete->m_pNext; delete pDelete; pDelete=pTmp; } m_NodeSum=0; pDelete=NULL; pTmp=NULL; } m_pHeader=NULL; } private: CNode *m_pHeader; int m_NodeSum; }; void main() { CList list; for(int i=0;i<5;i++) { CNode *pNode=new CNode(); pNode->m_Data=i; list. AddNode(pNode); } list.PassList(); }
(2)链表类模板
//链表类模板 #include<iostream.h> #include<iomanip.h> class CNode //节点类1 { public: CNode *m_pNext; int m_Data; CNode():m_pNext(NULL){} }; class CNet//节点类2 { public: CNet *m_pNext; int m_Data; CNet():m_pNext(NULL){} }; template<class T> class CList //链表类 { public: CList() { m_pHeader=NULL; m_NodeSum=0; } T* MoveTrail(T*pNode)//移动到尾节点 { T *pTmp=m_pHeader; for(int i=1;i<m_NodeSum;i++) { pTmp=pTmp->m_pNext; } return pTmp; } void AddNode(T*pNode)//添加节点 { if(0==m_NodeSum) { m_pHeader=pNode; } else { T *pTrail=MoveTrail(pNode); pTrail->m_pNext=pNode; } m_NodeSum++; } void PassList()//遍历链表 { if(m_NodeSum>0) { T *pTmp=m_pHeader; cout<<setw(5)<<pTmp->m_Data; for(int i=1;i<m_NodeSum;i++) { pTmp=pTmp->m_pNext; cout<<setw(5)<<pTmp->m_Data; } } cout<<endl; } ~CList()//定义链表的析构函数 { if(m_NodeSum>0) { T *pDelete=m_pHeader; T *pTmp=NULL; for(int i=1;i<m_NodeSum;i++) { pTmp=pDelete->m_pNext; delete pDelete; pDelete=pTmp; } m_NodeSum=0; pDelete=NULL; pTmp=NULL; } m_pHeader=NULL; } private: T *m_pHeader; int m_NodeSum; }; void main() { CList<CNode> list1; for(int i=0;i<5;i++) { CNode *pNode=new CNode(); pNode->m_Data=i; list1.AddNode(pNode); } list1.PassList(); CList<CNet> list2; for(int j=5;j<10;j++) { CNet *pNode=new CNet(); pNode->m_Data=j; list2.AddNode(pNode); } list2.PassList(); }
(3)