一元多项式的乘法C++

#include<iostream.h>
#include<stdlib.h>
typedef struct term{
 int z;   //指数
 float x;     //系数
 struct term *next;
}term;
struct term *creatlink();    //创建多项式
int cmp(int  a,int b);    //指数比较
struct term * addin(struct term *a,struct term *b);   //加法运算
void list(struct term *a);
struct term *multiply(struct term *a,struct term *b);

void main(){
struct term *A=creatlink();
list(A);
struct term *B=creatlink();
list(B);

struct term *D=multiply(A,B);
cout<<endl<<"乘法运算后:"<<endl;

list(D);
}

struct term *multiply(struct term *a,struct term *b){
struct term *result=(struct term *)malloc(sizeof(struct

term));result->next=NULL;
struct term *i;
struct term *h=(struct term *)malloc(sizeof(struct term));h-

>next=NULL;
struct term *j;
struct term *r;
for(i=a->next;i;i=i->next){
    r=h;h=r;
 for(j=b->next;j;j=j->next){
 struct term *p=(struct term *)malloc(sizeof(struct term));
 p->z=j->z+i->z;
 p->x=j->x*i->x;
    r->next=p;
 r=p;
 
 }
r->next=NULL;
addin(result,h);
h->next=NULL;
}
return result;
}
void list(struct term *a){
struct term *aa;
aa=a->next;
while(aa){
cout<<aa->x<<"X"<<aa->z;
if(aa->next!=0)
cout<<"+";
aa=aa->next;
}
}
struct term * addin(struct term *a,struct term *b){        //加法
struct term *ahead;
struct term *bhead;
struct term *aa;
struct term *bb;
ahead=a; bhead=b;
aa=ahead->next;  bb=bhead->next;
while(aa&&bb){
int result=cmp(aa->z,bb->z);
switch(result){
case 2:ahead=aa;aa=aa->next;break;   //指数小
case 1: bhead->next=bb->next;ahead->next=bb;bb->next=aa;ahead=ahead-

>next;bb=bhead->next;break;
case 0: aa->x+=bb->x;
 if(aa->x!=0)
 {ahead=aa;}
 else
 {ahead->next=aa->next;free(aa);}
 bhead->next=bb->next;free(bb);bb=bhead->next;aa=ahead-

>next;break;
}
}
if(bb)
{while(bb)
{bhead->next=bb->next;ahead->next=bb;ahead=bb;bb=bhead->next;}
free(bhead);}
if(aa)
{while(aa)
{ahead=aa;aa=aa->next;}
}
ahead->next=NULL;
return a;

}
int cmp(int a,int b){
if(a==b)
return 0;
if(a>b)
return 1;
else 
return 2;
}

struct term *creatlink(){              //创建多项式
struct term *p;
struct term *head;
struct term *q;
p=(struct term *)malloc(sizeof(struct term));
p->z=-1;
p->x=0;
p->next=NULL;
head=p;
cout<<endl<<"请输入多项式的项数:"<<endl;
int number0;
cin>>number0;
for(int i=1;i<=number0;i++){
q=(struct term *)malloc(sizeof(struct term));
cout<<"请输入第"<<i<<"项的系数和指数:"<<endl;
int n;
float m;
cin>>m>>n;
q->x=m;
q->z=n;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值