我编写了一个关于一元多项式相加的程序
//Ò»Ôª¶àÏîʽµÄÏà¼Ó#include<iostream.h>
#include<stdlib.h>
typedef struct Node
{
int coef ,expn;
struct Node * next;
}Linklist;
void CreatLinklist(Linklist *L,int n)//´´½¨Á´±í
{
Linklist * head,* pp,*qq;
int c,e;
head=L;//Ö¸ÏòÍ·½áµã
cout<<"Çë°´Ö¸Êý´ÓСµ½´óµÄ˳ÐòÊäÈë¶àÏîʽµÄϵÊýºÍÖ¸Êý:"<<endl;
for(int i=0;i<n;i++)
{
pp=(Linklist*)malloc(sizeof(Linklist));//¶¯Ì¬·ÖÅä´æ´¢¿Õ¼ä
if(!pp)
cout<<"allocation failure!"<<endl;
if(i<1)
{ head->next=pp;
qq=pp;
cin>>c>>e;
qq->coef=c;
qq->expn=e;
}
else
{
cin>>c>>e;
pp->coef=c;
pp->expn=e;
qq->next=pp;
qq=pp;
}
if(i==n-1) qq->next=NULL;
}
}
void OutputLinklist(Linklist * h,int n)//Êä³öÁ´±íÔªËغ¯Êý
{
for(int i=0;i<n;i++)
{
if(i<1||h->coef<0)
cout<<h->coef<<"x^"<<h->expn;
else
cout<<"+"<<h->coef<<"x^"<<h->expn;
h=h->next;//²»ÊÇh++
}
}
void main()
{
Linklist A,B,*p,*pp,*q,*qq,*w,*hA,*hB;
p=hA=&A;
q=hB=&B;//Ö¸ÏòÍ·½áµã
int numberA,numberB;//ÿ¸ö¶àÏîʽµÄÏîÊý
int n=0;
cout<<"ÇëÊäÈë¶àÏîʽAµÄ¸öÊý£º"<<endl;
cin>>numberA;
cout<<"ÇëÊäÈë¶àÏîʽBµÄ¸öÊý£º"<<endl;
cin>>numberB;
CreatLinklist(p,numberA);
CreatLinklist(q,numberB);
//p++; //´íÎó,Á´±íÖÐÖ¸ÕëÖ¸ÏòÏÂÒ»¸ö½áµã²»ÄÜÕâÑù±íʾ
//q++;
p=p->next;//Ö¸ÏòÁ´±íÖеÚÒ»¸ö½áµã
qq=q=q->next;
cout<<"¶àÏîʽAΪ:"<<endl<<"A=";
OutputLinklist(p,numberA);
cout<<endl;
cout<<"¶àÏîʽBΪ:"<<endl<<"B=";
OutputLinklist(q,numberB);
while(p&&q)
{
if(p->expn<q->expn)
{ pp=p;
p=p->next;
}
else if(p->expn==q->expn)
{
if(p->coef+q->coef)
{
p->coef=p->coef+q->coef;
pp=p;
p=p->next;
qq=q;
q=q->next;
}
}
else if(p==hA->next&&q==hB->next)
{
q=q->next;
w=qq;
qq=hB;
qq->next=q;
w->next=p;
hA->next=w;
numberA++;
}
else
{
w=q;
q=q->next;
qq->next=q;//´ÓBÁ´±íÖÐɾ³ýwËùÖ¸ÏòµÄ½áµã
w->next=p;//Á¬ÈëAÁ´±í
pp->next=w;
pp=w;
numberA++;//AÁ´±í¸öÊý×ÔÔö1
}
}
if(q)//½«BÁ´±íʣϵÄÔªËزåÈëµ½AÁ´±íÖÐ
{
pp->next=q;//pp-nextÖ¸ÏòBÁ´±íʣϵĽáµã
while(q)
{
q=q->next;
n++;//BÁ´±íʣϵĽáµã¸öÊý
}
numberA+=n;//AÁ´±í½áµãµÄ×ܸöÊý
}
cout<<endl;
p=&A;//ÈÃpÖ¸ÏòÁ´±íÊ×µØÖ·
p=p->next;
cout<<"Á½¶àÏîʽµÄºÍΪ:"<<endl<<"A+B=";
OutputLinklist(p,numberA);
}