合并顺序表和链式表

#define Listsize 100
#define Listincrease 50
typedef int elemtype;
#include<iostream>
using namespace std;
typedef struct{//顺序表
elemtype *e;
int length;
int size;
}Sqlist;
Initsqlist(Sqlist &L)
{
L.e=(elemtype*)malloc(Listsize*sizeof(elemtype));
if(!L.e)return 0;
L.length=0;
L.size=100;
return 1;
}
int shuru(Sqlist&L){
int i=0;
do{
cin>>L.e[i];
i++;
if(getchar()=='\n')
break;
}while(i);
L.length=i;
return 0;
}
int hebinsqlist(Sqlist&C,Sqlist A,Sqlist B){
Initsqlist(C);int i=0,j=0,m=0;
if(A.length+B.length>C.length)
{C.e=(elemtype*)realloc(C.e,(Listsize+Listincrease)*sizeof(elemtype));
C.size=Listsize+Listincrease;
}
while(i<A.length&&j<B.length){
if(A.e[i]<=B.e[j])
{C.e[m]=A.e[i];i++;m++;}
else 
{C.e[m]=B.e[j];j++;m++;}
}
while(i<A.length){C.e[m]=A.e[i];m++;i++;}
while(j<B.length){C.e[m]=B.e[j];m++;j++;}
C.length=A.length+B.length;
return 1;
}
int coutsqlist(Sqlist L){
int i=0;
while(i<L.length){
cout<<L.e[i]<<" ";
i++;
}
return 0;
}
typedef struct  Lnode{//链式表
struct Lnode*next;
elemtype e;
}Lnode,*Linklist;
 
int InitLinklist(Linklist&L)
{
L=(Linklist)malloc(sizeof(Lnode));
if(!L)return -1;
L->next=NULL;
return 0;


}
int shurulink(Linklist&L,int i){
int j;
Linklist A=L;
for(j=0;j<i;j++){
Linklist B;
B=(Linklist)malloc(sizeof(Lnode));
cin>>B->e;
B->next=A->next;
A->next=B;
A=B;
}
return 0;
}
int shuchu(Linklist L){
Linklist A=L->next;
while(A){
cout<<A->e<<" ";
A=A->next;
}
return 0;
}
int hebinlink(Linklist&C,Linklist A,Linklist B){
Linklist m=C;
Linklist p=A->next;
Linklist q=B->next;
while(p&&q){
if(p->e>=q->e){
Linklist v=q;
q=q->next;
v->next=m->next;
m->next=v;
m=v;
}
else{
Linklist u=p;
p=p->next;
u->next=m->next;
m->next=u;
m=u;
}
}
if(p){m->next=p;}
if(q){m->next=q;}
return 0;
}
int main(){
Sqlist A,B,C;
Initsqlist(A);
Initsqlist(B);
cout<<"=========顺序表==========================================="<<endl;
cout<<"请从小到大输入若干数字(空格作为分隔,回车结束输入)";
shuru(A);coutsqlist(A);cout<<endl;
cout<<"再输入一次"<<endl;
shuru(B);coutsqlist(B);cout<<endl;
hebinsqlist(C,A,B);
cout<<"顺序表合并"<<endl;
coutsqlist(C);
cout<<endl;
cout<<"=============链式表======================================="<<endl;
Linklist x,y,z;
InitLinklist(x);InitLinklist(y);InitLinklist(z);
cout<<"请从小到大输入五个数字"<<endl;
shurulink(x,5);
shuchu(x);cout<<endl;
cout<<"请从小到大输入五个数字"<<endl;
shurulink(y,5);
shuchu(y);cout<<endl;
cout<<"合并"<<endl;
hebinlink(z,x,y);
shuchu(z);cout<<endl;
return 0;
}












你可能感兴趣的:(合并顺序表和链式表)