Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239239
  • 博文数量: 91
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 955
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-12 09:38
文章分类

全部博文(91)

文章存档

2017年(1)

2011年(1)

2008年(15)

2007年(74)

我的朋友

分类: 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 prior
d=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;
}


阅读(1401) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~