#include<stdio.h>
#include<stdlib.h>
typedef struct term{//项的表示
float coef;//系数
int expn;//指数
struct term *next,*pre;
}*ElemType;
void createPolyn(ElemType &polyn)//创建一个多项式链表
{
polyn=(ElemType)malloc(sizeof(term));
ElemType q,p;
p=polyn;
polyn->next=q;
polyn->pre=NULL;
q->next=NULL;
q->pre=polyn;
for(int i=1;;i++)
{
q=(ElemType)malloc(sizeof(term));
printf("请输入第%d项系数和指数:",i);
scanf("%f%d",&q->coef,&q->expn);
p->next=q;
q->pre=p;
q->next=NULL;
if(q->coef==0 && q->expn==0)
break;
p=q;
}
}
void addPolyn(ElemType &p1,ElemType &p2)//多项式相加
{
ElemType polyn1=p1->next,polyn2=p2->next;
while(polyn1->next&&polyn2->next)
{
if(polyn2->expn > polyn1->expn)
polyn1=polyn1->next;
else if(polyn2->expn == polyn1->expn)
{
polyn1->coef+=polyn2->coef;
polyn1=polyn1->next;
polyn2=polyn2->next;
free(polyn2->pre);
}
else if(polyn2->expn < polyn1->expn)
{
ElemType pp=polyn2->next;
polyn1->pre->next=polyn2;
polyn2->next=polyn1;
polyn2->pre=polyn1->pre;
polyn1->pre=polyn2;
polyn2=pp;
}
}
while(polyn2->next)
{
polyn1->next=polyn2;
polyn1=polyn1->next;
polyn2=polyn2->next;
}
}
void subPolyn(ElemType &p1,ElemType &p2)
{
ElemType polyn1=p1,polyn2=p2;
while(polyn1->next&&polyn2->next)
{
if(polyn2->expn > polyn1->expn)
polyn1=polyn1->next;
else if(polyn2->expn == polyn1->expn)
{
polyn1->coef-=polyn2->coef;
polyn1=polyn1->next;
polyn2=polyn2->next;
free(polyn2->pre);
}
else if(polyn2->expn < polyn1->expn)
{
ElemType pp=polyn2->next;
polyn1->pre->next=polyn2;
polyn2->next=polyn1;
polyn2->pre=polyn1->pre;
polyn1->pre=polyn2;
polyn2=pp;
}
}
}
void printPolyn(ElemType polyn)//打印多项式
{
ElemType p;
p=polyn->next;
for(int i=1;p->next!=NULL;i++)
{
if(p->coef>0 && i!=1 && p->expn!=0)
printf("+%.2fx^%d",p->coef,p->expn);
else if(p->coef<0 && p->expn!=0)
printf("%.2fx^%d",p->coef,p->expn);
else if(p->coef>0 && i==1 && p->expn!=0)
printf("%.2fx^%d",p->coef,p->expn);
else if(p->coef>0 && i!=1 && p->expn==0)
printf("+%.2f",p->coef);
else if(p->coef<0 && p->expn==0)
printf("%.2f",p->coef);
else if(p->coef>0 && i==1 && p->expn==0)
printf("%.2f",p->coef);
p=p->next;
}
printf("\n");
}
int main()
{
ElemType polyn1,polyn2;
printf("请输入第一个多项式\n");
createPolyn(polyn1);
printPolyn(polyn1);
printf("请输入第二个多项式\n");
createPolyn(polyn2);
printPolyn(polyn2);
printf("两个多项式相加\n");
addPolyn(polyn1,polyn2);
printPolyn(polyn1);
printf("两个多项式相减\n");
subPolyn(polyn1,polyn2);
printPolyn(polyn1);
return 0;
}