linux administrator
jimonitu
全部博文(91)
2017年(1)
2011年(1)
2008年(15)
2007年(74)
kirsi17
1cpuer
zhjixi12
totola14
余散微习
cdm2135
screenpa
airmy
xyman_55
分类: LINUX
2008-03-03 16:20:37
单链表的模板类 #include <iostream.h> template <class T> class list { private: struct node { T data; node *next; }; node *head; public: list(); ~list(); void add(T &); void insert(T &, T &); //insert the second parameter after the first parameter void Delete(T &); void print(); void find(T &); }; template <class T> list<T>::list() { head=0; } template <class T> list<T>::~list() { node *p; while(p=head) { head=head->next; delete p; } } template <class T> void list<T>::add(T &t)//the new node put on the head { node *temp=new node; temp->data=t; temp->next=head; head=temp; } template <class T> void list<T>::insert(T &a, T &b) { node *temp=new node; node *p=head; temp->data=b; if(head->data==a)//the head node judge {temp->next=head; head=temp; } else { while((p->data!=a)&&p) { p=p->next; } if(p==0) cout<<"have not find"<<endl; else { temp->next=p->next; p->next=temp; } } } template <class T> void list<T>::find(T &c) { node *f=head; while(f&&(f->data!=c)) { f=f->next; } if(f==0) cout<<"have not find your need value"<<endl; else cout<<f->data<<endl; } template <class T> void list<T>::Delete(T &de) { node *d=head; node *q; if(head->data==de) { q=head; head=head->next; } else { while((d->next)&&(d->next->data!=de))//d is the delete node's priord=d->next;if(d->next==0)cout<<"delete node have not find"<else{q=d->next;d->next=d->next->next;}}delete q;}template void list::print(){node *pr=head;while(pr){cout<data<pr=pr->next;}}int main(){list li;for(int i=0;i<10;i++)li.add(i);li.print();int a1=5,a2=15,a3=7;li.insert(a1,a2);li.print();li.Delete(a1);li.print();li.find(a3);return 0;}
上一篇:virtual function and abstract class
下一篇:栈和队列的类模板
登录 注册