#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
//多项式表示
typedef struct PolyNode *Poly;
struct PolyNode
{
int coef;//系数
int expon;//指数
Poly Link;//指针
};
void Attach(int c,int e,Poly *pReal)
{
Poly p;
p=(Poly)malloc(sizeof(struct PolyNode));
p->coef=c;
p->expon=e;
p->Link=NULL;
(*pReal)->Link=p;
*pReal=p;
}
Poly ReadPoly()//读入多项式
{
int N,c,e;
Poly p,t,Real;
p=(Poly)malloc(sizeof(struct PolyNode));
p->Link=NULL;
Real=p;
scanf("%d",&N);
while(N--)
{
scanf("%d %d",&c,&e);
Attach(c,e,&Real);
}
t=p;
p=p->Link;
free(t);
return p;
}
Poly Mult(Poly p1,Poly p2)//相乘
{
Poly t1,t2,p,Real,t;
int c,e;
if(!p1||!p2)return NULL;
t1=p1;t2=p2;
p=(Poly)malloc(sizeof(struct PolyNode));
p->Link=NULL;
Real=p;
while(t2)//t2的每一项去成t1的第一项
{
Attach(t1->coef*t2->coef,t1->expon+t2->expon,&Real);
t2=t2->Link;
}
t1=t1->Link;//t1h后移一项
while(t1)
{
t2=p2;
Real=p;
while(t2)
{
c=t1->coef*t2->coef;
e=t1->expon+t2->expon;
while(Real->Link&&Real->Link->expon>e)//寻找比他次数小的就退出循环
Real=Real->Link;
if(Real->Link&&Real->Link->expon==e)//如果次数相等,判断相加是否为0
{
if(!(c+Real->Link->coef))//相加等于0,删除
{
t=Real->Link;
Real->Link=t->Link;
free(t);
}
else
{
Real->Link->coef+=c;
}
}
else//次数不相等插入
{
t=(Poly)malloc(sizeof(struct PolyNode));
t->coef=c;
t->expon=e;
t->Link=NULL;
t->Link=Real->Link;
Real->Link=t;
Real=Real->Link;
}
t2=t2->Link;
}
t1=t1->Link;
}
t2=p;p=p->Link;
free(t2);
return p;
}
void PrintPoly(Poly p)//输出多项式
{
int f=0;//用来判断第一项
if(!p)
{
printf("0 0\n");
return;
}
while(p)
{
if(f==0)
f=1;
else
printf(" ");
printf("%d %d",p->coef,p->expon);
p=p->Link;
}
printf("\n");
}
Poly Add(Poly p1,Poly p2)//相加
{
Poly p,Real,t1,t2,t;
int c,e;
t1=p1;t2=p2;
p=(Poly)malloc(sizeof(struct PolyNode));
p->Link=NULL;
Real=p;
while(t1&&t2)
{
if(t1->expon==t2->expon)
{
if(t1->coef+t2->coef==0)
{
t1=t1->Link;
t2=t2->Link;
}
else
{
c=t1->coef+t2->coef;
e=t1->expon;
Attach(c,e,&Real);
t1=t1->Link;
t2=t2->Link;
}
}
else if(t1->expon>t2->expon)
{
c=t1->coef;
e=t1->expon;
Attach(c,e,&Real);
t1=t1->Link;
}
else
{
c=t2->coef;
e=t2->expon;
Attach(c,e,&Real);
t2=t2->Link;
}
}
while(t1)
{
c=t1->coef;
e=t1->expon;
Attach(c,e,&Real);
t1=t1->Link;
}
while(t2)
{
c=t2->coef;
e=t2->expon;
Attach(c,e,&Real);
t2=t2->Link;
}
t=p;
p=p->Link;
free(t);
return p;
}
int main()
{
Poly p1,p2,pp,ps;
p1=ReadPoly();
p2=ReadPoly();
pp=Mult(p1,p2);
PrintPoly(pp);
ps=Add(p1,p2);
PrintPoly(ps);
}
一元多项式的乘法与加法运算
最新推荐文章于 2020-12-04 05:43:02 发布