#include "stdafx.h" #include "linklist.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[])//super man yes { linklist<int>mylinklist; mylinklist.InsertNode(1,1); mylinklist.InsertNode(2,2); mylinklist.InsertNode(2,3); mylinklist.InsertNode(3,4); mylinklist.DeleteNode(2); mylinklist.PrintNode(); getchar(); return 0; }
#pragma once #include <iostream> using namespace std; template<class T> class linklist { public: linklist():length(0),mlist(nullptr){} ~linklist(){} public: bool IsEmpty(); linklist<T>* InsertNode(int index,T value); linklist<T>* DeleteNode(int index); linklist<T>* ChangeNodeValue(int index ,T value); void PrintNode(); void Clear(); int GetLenght(); private: typedef struct Node { int index; T value; struct Node * next; }node,*pnode; private: pnode mlist; int length; }; template<class T> bool linklist<T>::IsEmpty( )//verity whether the linklist is empty! { if(this->mlist==nullptr) { return true; } return false; } template<class T> linklist<T>* linklist<T>::InsertNode(int Index,T value)//insert the node pointer of the mlist ,can't ne used as the move pointer~ { pnode pnewnode = new node; pnode tempnode=mlist; memset(pnewnode, 0, sizeof(node)); memcpy_s(&pnewnode->value ,sizeof(T), &value,sizeof(T)); if(Index-1<=length) { if(mlist==nullptr&&Index==1) { mlist=pnewnode; length++; return this; } for(int j=1;j<Index-1;j++) { mlist=mlist->next; } pnewnode->next=mlist->next; mlist->next=pnewnode; length++; this->mlist=tempnode; return this ; } else return NULL; } template<class T> linklist<T>* linklist<T>::DeleteNode(int Index) { pnode tempnode; pnode nodetp; tempnode=mlist; if(Index>length||Index<0) { return 0; } if(1==Index) { delete mlist; } for(int j=1;j<Index-1;j++) mlist=mlist->next; nodetp=mlist->next; mlist->next=mlist->next->next; length--; delete nodetp; this->mlist=tempnode; return this; } template<class T> linklist<T>* linklist<T>::ChangeNodeValue(int Index,T value) { pnode tempnode;//the temp node is just the return node to flag the old linklist pointer if(Index<0||Index>length) { return 0; } for(int j=1;j<=Index;j++) { mlist=mlist->next; } mlist->value=value; this->mlist=tempnode; return this; } template<class T> void linklist<T>::Clear() { pnode tempnode; if(0==length) return NULL; while(mlist) { tempnode=mlist->next;//every time delete mlist; mlist=tempnode; } } template<class T> int linklist<T>::GetLenght() { return length; } template<class T> void linklist<T>::PrintNode() { while(length>0) { cout<<mlist->value<<' '<<endl; mlist=mlist->next; length--; } }
链表的实现基于C++
最新推荐文章于 2022-08-12 17:52:37 发布