一元多项式乘法

#include<iostream>
#include<malloc.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
typedef struct node
{
float xs;
int zs;
struct node *next;
}lnode,*linklist;

linklist creat()
{
lnode *p,*q,*s;
lnode *head=NULL;
int zs;
float xs;
head=(linklist)malloc(sizeof(lnode));
if(!head)
return NULL;
head->xs=0;
head->zs=0;
head->next=NULL;
do
{
printf("输入系数xs(系数和指数都为零时结束)");
cin>>xs;
printf("输入系数zs(系数和指数都为零时结束)");
cin>>zs;
if(xs==0&&zs==0)
{
break;
}
s=(linklist)malloc(sizeof(lnode));
if(!s)
return NULL;
s->zs=zs;
s->xs=xs;
q=head->next;
p=head;
while(q&&zs<q->zs)
{
p=q;
q=q->next;
}
if(q==NULL||zs>q->zs)
{
p->next=s;
s->next=q;
}
else
q->xs +=xs;
}while(1);
return head;
}
lnode *reverse(linklist head)
{
lnode *q,*r,*p=NULL;
q=head->next;
while(q)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
head->next=p;
return head;
}
lnode * mul(linklist A,linklist B)
{
lnode *pa,*pb,*pc,*u,*head;
int k,maxexp;
float xs;
head=(linklist)malloc(sizeof(lnode));
if(!head)
return NULL;
head->xs=0.0;
head->zs=0;
head->next=NULL;
if(A->next!=NULL && B->next!=NULL)
maxexp =A->next->zs+B->next->zs;
else
return head;
pc=head;
B=reverse(B);
for(k=maxexp;k>=0;k--)
{
pa=A->next;
while(pa!=NULL&&pa->zs>k)
pa=pa->next;
pb=B->next;
while(pb!=NULL&&pa!=NULL&&pa->zs+pb->zs < k)
pb=pb->next;
xs=0.0;
while(pa!=NULL&&pb!=NULL)
{
if(pa->zs+pb->zs==k)
{
xs+=pa->xs * pb->xs ;
pa=pa->next;
pb=pb->next;
}
else if(pa->zs+pb->zs > k)
pa=pa->next;
else
pb=pb->next;
}
if(xs!=0.0)
{
u=(linklist)malloc(sizeof(lnode));
u->xs=xs;
u->zs=k;
u->next=pc->next;
pc->next=u;
pc=u;
}
}
B=reverse(B);
return head;
}

void output(linklist head)
{
lnode *p=head->next;
while(p)
{
cout<<p->xs ;
if(p->zs)
cout<<"*x^"<<p->zs ;
if(p->next&&p->next->xs>0)
cout<<"+";
p=p->next;
}
}
int main()
{
linklist A,B,C;
A=creat();
cout<<"A(X)=";
output(A);
cout<<endl;
B=creat();
cout<<"B(X)=";
output(B);
cout<<endl;
C=mul(A,B);
printf("C(X)=A(X) * B(X)=");
output(C);
cout<<endl;

}

 

 

转载于:https://www.cnblogs.com/mykonons/p/6596671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值