#include "iostream"
using namespace std;
typedef int status;
typedef struct PNode
{
float coef;//系数
int expn;//指数
struct PNode *next;
}PNode,*Polynomial;
status CreatePolyn(Polynomial &P,int n)
{
P=new PNode;
Polynomial s,pre,q;
P->next=NULL;
for(int i=1;i<=n;i++)
{
s=new PNode;
cin>>s->coef>>s->expn;
pre=P;
q=P->next;
while(q&&q->expn<s->expn)
{
pre=q;
q=q->next;
}
s->next=q;
pre->next=s;
}
}
status AddLNode(Polynomial &pa,Polynomial &pb)
{
Polynomial p1,p2,p3,r;
int sum;
p1=pa->next;
p2=pb->next;
p3=pa;
while(p1&&p2)
{
if(p1->expn==p2->expn)
{
sum=p1->coef+p2->coef;
if(sum!=0)
{
p1->coef=sum;
p3->next=p1;
p3=p1;
p1=p1->next;
r=p2;
p2=p2->next;
delete r;
}
else {
r=p1;
p1=p1->next;
delete r;
r=p2;
p2=p2->next;
delete r;
}
}else if(p1->expn<p2->expn)
{
p3->next=p1;
p3=p1;
p1=p1->next;
}
else
{
p3->next=p2;
p3=p2;
p2=p2->next;
}
}
p3->next=p1?p1:p2;
delete pb;
}
status printPnode(Polynomial &P)
{
int x;
Polynomial temp;
temp=P->next;
while(temp!=NULL)
{
cout<<temp->coef<<"x^"<<temp->expn<<endl;
temp=temp->next;
}
}
int main()
{
Polynomial p1,p2,p3;
cout<<"请输入第一个多项式:"<<endl;
CreatePolyn(p1,5);
printPnode(p1);
cout<<"请输入第二个多项式为:"<<endl;
CreatePolyn(p2,5);
printPnode(p2);
cout<<"多项式的加法和为:"<<endl;
AddLNode(p1,p2);
printPnode(p1);
}
利用线性表实现多项式加法
最新推荐文章于 2022-04-26 23:30:25 发布