一元多项式相加,相减与相加类似。
链表应用
完整代码:
#include<iostream>
#include<malloc.h>
#include<cstring>
using namespace std;
typedef struct LNode
{
struct LNode *next;
int exp; //index
int coef; //coefficient
}*Linklist,LNode;
void InitLinklist(Linklist &L)
{
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
}
void CreatPloy(Linklist &L)
{
Linklist p,q;
int co,ex;
p=L;
cout<<"Input the index and coefficient, 0 0 to end."<<endl;
while(true) // end
{
cin>>co>>ex;
if(!co) break; //0x^b end input
q=(LNode*)malloc(sizeof(LNode));
q->coef=co;
q->exp=ex;
p->next=q;
p=q;
}
p->next=NULL;
}
Linklist AddPloy(Linklist L1,Linklist L2)
{
Linklist L,p,q,r,s;
r=L=(LNode*)malloc(sizeof(LNode));
p=L1->next;
q=L2->next;
while(p!=NULL && q!=NULL)
{
if(p->exp==q->exp)
{
if((p->coef+q->coef)!=0) //pass ax^b+cx^b=0x^b
{
s=(LNode*)malloc(sizeof(LNode));
s->coef=p->coef+q->coef;
s->exp=p->exp;
r->next=s;
r=s;
}
p=p->next;
q=q->next;
}
else if(p->exp>q->exp)
{
r->next=q;
r=q;
q=q->next;
}
else
{
r->next=p;
r=p;
p=p->next;
}
}
while(p!=NULL)
{
r->next=p;
r=p;
p=p->next;
}
while(q!=NULL)
{
r->next=q;
r=q;
q=q->next;
}
r->next=NULL;
return L;
}
Linklist MinusPloy(Linklist L1,Linklist L2)
{
Linklist p,q,r,L,s;
r=L=(LNode*)malloc(sizeof(LNode));
p=L1->next;
q=L2->next;
while(p!=NULL && q!=NULL)
{
if(p->exp==q->exp)
{
if((p->coef-q->coef)!=0)
{
s=(LNode*)malloc(sizeof(LNode));
s->coef=p->coef-q->coef;
s->exp=p->exp;
r->next=s;
r=s;
}
p=p->next;
q=q->next;
}
else if(p->exp>q->exp)
{
q->coef=-q->coef;
r->next=q;
r=q;
q=q->next;
}
else
{
r->next=p;
r=p;
p=p->next;
}
}
while(p!=NULL)
{
r->next=p;
r=p;
p=p->next;
}
while(q!=NULL)
{
q->coef=-q->coef;
r->next=q;
r=q;
q=q->next;
}
r->next=NULL;
return L;
}
int main()
{
Linklist Link1,Link2,p,Link;
cout<<"Creat Ploy 1"<<endl;
InitLinklist(Link1);
CreatPloy(Link1);
cout<<"Creat Ploy 2"<<endl;
InitLinklist(Link2);
CreatPloy(Link2);
cout<<"The two ploy:"<<endl;
for(p=Link1->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;
for(p=Link2->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;
cout<<"Now Ploy1+Ploy2:"<<endl;
Link=AddPloy(Link1,Link2);
cout<<"After add:"<<endl;
for(p=Link->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;
Link=MinusPloy(Link1,Link2);
cout<<"After Minus:"<<endl;
for(p=Link->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;
/*cout<<"The two ploy:"<<endl;
for(p=Link1->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;
for(p=Link2->next;p->next!=NULL;p=p->next)
cout<<p->coef<<"X^"<<p->exp<<"+";
cout<<p->coef<<"X^"<<p->exp<<endl;
cout<<endl;*/
return 0;
}