#include<stdio.h>
#include<stdlib.h>
structpnode//鏈表的組成
{
float coef;
intexpn;
structpnode*next;
} polynode;
struct pnode *Creat(int n)//創建一鏈表
{ struct pnode *L,*p,*q;
int i;
q=L=(struct pnode *)malloc(sizeof(polynode));
L->next=NULL;
for(i=0;i<n;i++)
{p=(struct pnode *)malloc(sizeof(polynode));
scanf("%f%d",&p->coef,&p->expn);
p->next=L->next;
L->next=p;
}
return q;}
struct pnode*polyadd(struct pnode *LA,struct pnode *LB)
//實現A多項式加B多項式等於C多項式,並返回C多項式
//的表頭指針
{ struct pnode *LC,*pc,*pa,*pb;
floatx;
pa=LA->next;
pb=LB->next ;
pc=(struct pnode *)malloc(sizeof(polynode));
LC=pc;
while (pa&&pb)
{if(pa->expn==pb->expn)//同類項合並
{x=pa->coef+pb->coef;
if(x!=0)
{pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=x;
pc->expn=pa->expn;
}
pa=pa->next;
pb=pb->next;
}
else
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
if (pa->expn<pb->expn)//a的指數小於b的指數
{ pc->coef=pa->coef;
pc->expn=pa->expn;
pa=pa->next;}
else
{ pc->coef=pb->coef;
pc->expn=pb->expn;
pb=pb->next; }
}
}
while(pa)//還乘下 a 多項式
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=pa->coef;
pc->expn=pa->expn;
pa=pa->next;
}
while(pb)//還乘 下b 多項式
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=pb->coef;
pc->expn=pb->expn;
pb=pb->next;
}
pc->next=NULL;
returnLC;
}
struct pnode *print(struct pnode *L)//鏈表的打印
{
while(L->next->next)
{ L=L->next;
printf("%.2f^%d+",L->coef,L->expn);
}
L=L->next;
printf("%.2f^%d\n",L->coef,L->expn);
return L;
}
void main()
{ struct pnode *PA,*PB,*PC;
int i;
printf("請輸入多項式項數");//創建一鏈表PA
scanf("%d",&i);
PA=Creat(i);
printf("請輸入另一多項式項數");//創建一鏈表PB
scanf("%d",&i);
PB=Creat(i);
PC=polyadd( PA, PB);//得到鏈表PC
printf("多項式A=");
print(PA);
printf("多項式B=");
print(PB);
printf("運算後多項式=");
print(PC);
}