#include <stdio.h>
#include <malloc.h>
#define NULL 0
struct node
{
int a,n;
struct node *next;
};
struct node *creat()
{
int a,n;
struct node *p1,*p2,*head;
head=NULL;
scanf("%d%d",&a,&n);
p2=NULL;
while(a)
{
p1=(struct node *) malloc(sizeof(struct node));
p1->a=a;
p1->n=n;
p1->next=NULL;
if(head==NULL)
{
head=p1;p2=p1;
}
else
{
p2->next=p1;
p2=p1;
}
scanf("%d%d",&a,&n);
}
return head;
}
struct node *add(struct node *head1,struct node *head2)
{
int a,n;
struct node *p1=head1,*p2=head2,*head,*p3,*p4,*p;
head=NULL;
while(p1 && p2)
{
if(p1->n==p2->n)
{
a=p1->a+p2->a;
n=p1->n;
p1=p1->next;
p2=p2->next;
}
else
{
if(p1->n>p2->n)
{
a=p1->a;n=p1->n;
p1=p1->next;
}
else
{
a=p2->a;n=p2->n;
p2=p2->next;
}
}
if(a)
{
p3=(struct node *)malloc(sizeof(struct node));
p3->a=a;
p3->n=n;
p3->next=NULL;
if(head==NULL)
{
head=p3;p4=p3;
}
else
{
p4->next=p3;
p4=p3;
}
}
}
p=p1?p1:p2;
while(p)
{
p3=(struct node *)malloc(sizeof(struct node));
p3->a=p->a;
p3->n=p->n;
p3->next=NULL;
if(head==NULL)
{
head=p3;p4=p3;
}
else
{
p4->next=p3;
p4=p3;
}
p=p->next;
}
return head;
}
void print(struct node *head)
{
struct node *p1=head;
if(head==NULL)
{ printf("此多项式不存在
");
return ;
}
printf("
");
if(p1)
{
printf("%dx%d",p1->a,p1->n);
p1=p1->next;
}
while(p1)
{
if(p1->a>0)
printf("+");
if(p1->n==0)
printf("%d",p1->a);
else
if(p1->a==1)
printf("x%d",p1->n);
else
printf("%dx%d",p1->a,p1->n);
p1=p1->next;
}
printf("
");
}
int main()
{
struct node *head1,*head2,*head3;
head1=creat();
head2=creat();
print(head1);
print(head2);
head3=add(head1,head2);
print(head3);
}