首先定義一個節點類
template <class datatype>//表格類型數據通用模板
class Node{ //定義節點類
public:
datatype data;
Node<datatype> *next;
};
其中含有該節點的數據元素信息以及指向下一個節點的指針,datatype數據模板中包含int 和chr等常見數據類型
接下來定義一個鏈表類其中用到節點類
class List{ private: Node<datatype> *head;//頭結點類 public: List(){head =NULL;}//構造函數 int length(); //求表長函數 bool get_date(int i, datatype &x);//取表中元素 bool insert_data(datatype data,int i);//從i位置插入元素 bool delet_dataa(int i);//刪除元素 void prine_List();//打印元素 ~List(){ Node<datatype> *p; while(head){ p=head; head=head->next; delete p; } }; };
其中private中定義了每條鏈表中的頭結點信息,形成封裝的概念,該鏈表只能同過public中函數訪問head節點來訪問鏈表中的每個元素
接下來是有關於成員函數的定義,主要和每個人的算法實現有關,這里不做詳細介紹
template <class datatype> int List<datatype>::length(){ int i=0; Node<datatype> *current=head; while(current) { i++; current=current->next; } return i; }
template <class datatype> bool List<datatype>::get_date(int i,datatype &b ){ int j,x; if(i<1||i>length()+1) { cout<<"can't find posation of message"<<endl; return false;} for(j=1;j<i;j++){ x=head->data; head=head->next; } cout<<x<<endl; return true; }
template <class datatype> bool List<datatype>::insert_data(datatype data,int i){ Node<datatype> *current, *previous ,*newnode; int j=1; if ((i>length()+1)||(i<0)) { cout<<"this is a error posation"<<endl; return false; } newnode=new Node<datatype>; if(newnode==NULL) { cout<<"don't have posation to storage it "<<endl; } newnode->data=data; newnode->next=NULL; if(i==1){ newnode->next=head; head=newnode; return true; } current=previous=head; while(current!=NULL&&j<i) { previous=current; current=current->next; j++; } newnode->next=current; previous->next=newnode; return true; }
template <class datatype> void List<datatype>::prine_List() { Node<datatype> *current; current=head; while(current){ cout<<current->data<<" "; current=current->next; } cout<<endl; }
主函數測試
int main() { List<int> fist_list; int i; for(i=1;i<5;i++) { fist_list.insert_data(i*100,1); } cout<<"ouput_data:\n"; fist_list.prine_List(); fist_list.~List(); return 0;

