[分享]
#include <iostream.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct SLNode
{
elemtype coef;
elemtype exp;
struct SLNode *Next;
}slnodetype;
int MergeSL(slnodetype *la,slnodetype *lb,slnodetype **lc);
int CreateSL(slnodetype *la,int n);
void DisplaySL(slnodetype *la,char *comment);
void main()
{
slnodetype *la,*lb,*lc,*p;
int m,n;
if((la=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
la->Next=NULL;
if((lb=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
lb->Next=NULL;
cout<<"How many points in la:"<<" ";
cin>>m;
cout<<"How many points in lb:"<<" ";
cin>>n;
cout<<"\nEnter la的系数和指数:\n";
CreateSL(la,m);
cout<<"\nEnter lb的系数和指数:\n";
CreateSL(lb,n);
MergeSL(la,lb,&lc);
DisplaySL(lc,"The result:");
}
int MergeSL(slnodetype *la,slnodetype *lb,slnodetype **lc)
{
slnodetype *pa,*pb,*pc;
int t;
if((*lc=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pa=la->Next;
pb=lb->Next;
pc=*lc;
while(pa&&pb)
{
if(pa->exp==pb->exp)
{
t=pa->coef+pb->coef;
if(t!=0)
{
if((pc->Next=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pc=pc->Next;
pc->coef=t;
pc->exp=pa->exp;
}
pa=pa->Next;
pb=pb->Next;
}
else if(pa->exp<pb->exp)
{
if((pc->Next=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pc=pc->Next;
pc->exp=pa->exp;
pc->coef=pa->coef;
pa=pa->Next;
}
else
{
if((pc->Next=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pc=pc->Next;
pc->exp=pb->exp;
pc->coef=pb->coef;
pb=pb->Next;
}
}
while(pa!=NULL)
{
if((pc->Next=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pc=pc->Next;
pc->coef=pa->coef;
pc->exp=pa->exp;
pa=pa->Next;
}
while(pb!=NULL)
{
if((pc->Next=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
pc=pc->Next;
pc->coef=pb->coef;
pc->exp=pb->exp;
pb=pb->Next;
}
pc->Next=NULL;
return 1;
}
int CreateSL(slnodetype *la,int n)
{
int i;
slnodetype *p,*q;
q=la;
for(i=1;i<=n;i++)
{
if((p=(slnodetype *)malloc(sizeof(slnodetype)))!=NULL)
cin>>(p->coef)>>(p->exp);
q->Next=p;
q=p;
}
q->Next=NULL;
return 1;
}
void DisplaySL(slnodetype *la,char *comment)
{
slnodetype *p;
p=la->Next;
cout<<"结果如下:"<<endl;
while(p)
{
cout<<p->coef<<" "<<p->exp<<endl;
p=p->Next;
}
cout<<endl;
}