AH=1-3X(6)+7X(12)
BH=-X(4)+3X(6)-9X(10)+8X(14)
#include<iostream>
using namespace std;
struct elem
{
int coef;
int exp;
elem *next;
};
void creat(int a[],int b[],elem *&head,int n)
{//尾插法
head=new elem;
head->next=NULL;
elem *rear,*s;
rear=head;
for(int i=0;i<n;i++)
{
s=new elem;
s->coef=a[i];
s->exp=b[i];
s->next=NULL;
rear->next=s;
rear=s;
}
}
void show(elem *&head)
{
elem *p=head->next;
while(p!=NULL)
{
cout<<p->coef<<" "<<p->exp<<" ";
p=p->next;
}
cout<<endl;
}
void add(elem *&head1,elem *&head2)
{
elem *p,*q,*pre,*qre;
pre=head1;
qre=head2;
p=pre->next;
q=qre->next;
while(p!=NULL&&q!=NULL)
{ //三种情况
if(p->exp<q->exp)
{
p=p->next;
pre=pre->next;
}
else if(p->exp>q->exp)
{
elem *v=q->next;
pre->next=q;
pre=pre->next;
q->next=p;
q=v;
qre->next=q;
}
else if(p->exp==q->exp)
{
p->coef=p->coef+q->coef;
if(p->coef==0)
{
elem *t=p;
p=p->next;
pre->next=p;
delete t;
}
else
{
p=p->next;
pre=pre->next;
}
elem *t=q;
q=q->next;
qre->next=q;
delete t;
}//注意保证q和qre,p和pre的前后关系
}
if(q!=NULL)//最后将剩余q的项,接到pre->next后面
{
pre->next=q;
}
delete head2;
}
int main()
{
elem *head1,*head2;
int a[10]={1,-3,7};
int b[10]={0,6,12};
int c[10]={-1,3,-9,8};
int d[10]={4,6,10,14};
/*int a[10]={1,-2};
int b[10]={0,2};
int c[10]={2,2};
int d[10]={0,2};*/
creat(a,b,head1,3);
show(head1);
creat(c,d,head2,4);
show(head2);
add(head1,head2);
show(head1);
return 0;
}