多项式相加求值怎样用C++代码实现

如题所述

多项式相加,也就是合并同类项。
#include <iostream>
using namespace std;
struct list
{
int coef;//系数
int exp;//指数
list *next;
};
list *Creat()//创建带头结点的链表
{
list *h,*r,*s;//h是头结点,存放项的个数,指向第一项
r=h=new list;
h->next=NULL;
while(1)
{
s=new list;
cin>>s->coef>>s->exp;
if(s->coef==0)
break;
if(h->next==NULL)
{
r=s;//r=h->next
h->next=r;
}
else
{
r->next=s;
r=s;
}
}
r->next=NULL;
return h;
}
void Display(list *h)//输出链表
{
list *p;
p=h->next;
cout<<"f(x)=";
while(p)
{
if(p->next!=NULL)
cout<<p->coef<<"X^"<<p->exp<<"+";
else
cout<<p->coef<<"X^"<<p->exp;
p=p->next;
}
cout<<endl;
}
list *Huajian(list *h1)//合并同类项
{
list *p1,*q1,*q2;
for(p1=h1->next;p1;p1=p1->next)
for(q1=p1,q2=q1->next;q2;q1=q2,q2=q2->next)
if(p1->exp==q2->exp)
{
p1->coef+=q2->coef;
q1->next=q2->next;
delete q2;
q2=q1;//q2=q1->next;
}
return h1;
}
list *Multiply(list *h1,list *h2)//实现两个链表相乘
{
list *p1,*p2,*q1;
int c,e;
p1=h1->next;
p2=p1->next;
q1=h2->next;
do
{
c=p1->coef;
e=p1->exp;
while(q1)
{
p1->coef=c*q1->coef;
p1->exp=e+q1->exp;
if(q1->next!=NULL)
{
p1->next=new list;
p1=p1->next;
}
q1=q1->next;
}
q1=h2->next;
p1->next=p2;
p1=p2;
if(p2->next!=NULL)
p2=p2->next;
}while(p2);
h1=Huajian(h1);
return h1;
}
main()
{
list *h1,*h2;
h1=Creat();
Display(h1);
h2=Creat();
Display(h2);
h1=Multiply(h1,h2);
Display(h1);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答