首先定义一个节点类
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;