如何将单链表转换成双链表
#include<iostream.h>#include<string.h>
#define N 5
class user
{
friend class node;
private:
char *name;
long code;
user *next;
public:
void setName(char *na);
void setCode(long c);
char* getName();
long getCode();
void dispName();
void dispCode();
};
void user::setName(char *na)
{
name = new char(strlen(na)+1);
if(name!=NULL)
{
strcpy(name, na);
}
}
void user::setCode(long c)
{
code = c;
}
char * user::getName()
{
return name;
}
long user::getCode()
{
return code;
}
void user::dispName()
{
cout<<name<<" ";
}
void user::dispCode()
{
cout<<code<<endl;
}
class node
{
protected:
user *head, *tail;
public:
node()
{
head=NULL;
tail=NULL;
}
~node()
{}
void Puttail(char *na, long num)//链表尾法,建立数据链表
{
user *p=new user;
if(head==NULL)
{
head=p;
tail=p;
}
p->setName(na);
p->setCode(num);
p->next = NULL;
tail->next = p;
tail = p;
}
void find(long x,user s[])//按电话号码查找用户信息
{
long low=0, high=N-1, mid;
low = 0;
high = N-1;
while(low<=high)
{
mid = (low+high)/2;
if(x==s[mid].getCode())
{
break;
}
else if(x>s[mid].getCode())high=mid-1;
else low=mid+1;
}
cout<<"找到该用户的信息为:"<<"第"<<mid+1<<"个 ";
s[mid].dispName();
s[mid].dispCode();
}
void find(char *a,user s[])//按名字顺序查找用户信息
{
int i;
for(i=0;i<N;i++)
{
if(strcmp(a,s[i].getName())==0)break;
}
cout<<"找到该用户的信息为:"<<"第"<<i+1<<"个 ";
s[i].dispName();
s[i].dispCode();
}
void show()//链表的输出
{
user *p;
p=head;
while(p!=NULL)
{
cout<<(*p).getName()<<" ";
cout<<(*p).getCode()<<endl;
p=p->next;
}
}
};
void main()
{
int i,j;
user a[N],b,c[N],d[N];
node x,y;
char na[20],na1[20];
long num,num1;
for(i=0; i<N; i++)
{
cout<<"输入第"<<i+1<<"个人的姓名:";
cin>>na;
cout<<"输入第"<<i+1<<"个人的电话:";
cin>>num;
cout<<endl;
a[i].setName(na) ;
a[i].setCode(num) ;
c[i]=a[i];
d[i]=a[i];
}
for(i=1;i<=N; i++)//按号码冒号排序
{
for(j=0;j<N-i;j++)
{
if(c[j].getCode()<c[j+1].getCode())
{
b=c[j];
c[j]=c[j+1];
c[j+1]=b;
}
}
}
for(i=1;i<N; i++)//按名字冒号排序
{
for(j=0;j<N-i;j++)
if(strcmp(d[j].getName(),d[j+1].getName())<0)
{
b=d[j];
d[j]=d[j+1];
d[j+1]=b;
}
}
for(i=0;i<N; i++)
{
x.Puttail(c[i].getName(), c[i].getCode());
y.Puttail(d[i].getName(), d[i].getCode());
}
cout<<"按电话号码由大到小输出"<<endl;
x.show();
cout<<endl;
cout<<"请输入要查找用户的号码:";
cin>>num1;
x.find(num1,c);
cout<<endl;
cout<<"按名字顺序由大到小输出"<<endl;
y.show();
cout<<endl;
cout<<"请输入要查找用户的名字:";
cin>>na1;
y.find(na1,d);
}