#include<iostream>
using namespace std;
typedef struct LNode
{
float coef;
int expn;
LNode *next;
}LNode,*LinkList;
void CreateList_L(LinkList &L,int n)
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=n;i>0;i--)
{
LinkList p=(LinkList)malloc(sizeof(LNode));
cin>>p->coef>>p->expn;
p->next=L->next;
L->next=p;
}
}
void AddPolyn(LinkList &L1,LinkList &L2)
{
LinkList h=L1;
LinkList p1=L1->next;
LinkList p2=L2->next;
while(p1&&p2)
{
if(p1->expn<p2->expn)
{
h=h->next;
p1=p1->next;
}
else if(p1->expn>p2->expn)
{
L2->next=p2->next;
p2->next=p1;
h->next=p2;
h=h->next;
p2=L2->next;
}
else
{
if(p1->coef+p2->coef==0)
{
h->next=p1->next;
free(p1);
p1=h->next;
L2->next=p2->next;
free(p2);
p2=L2->next;
}
else
{
p1->coef=p1->coef+p2->coef;
h=h->next;
p1=p1->next;
L2->next=p2->next;
free(p2);
p2=L2->next;
}
}
}
while(p2)h->next=p2;
free(L2);
}
void Visit(LinkList L)
{
LinkList p=L->next;
while(p)
{
cout<<p->coef<<"x^"<<p->expn;
p=p->next;
if(p)cout<<'+';
}
}
int main()
{
LinkList L1,L2;
cout<<"input L1:"<<endl;
CreateList_L(L1,4);
cout<<"input L2:"<<endl;
CreateList_L(L2,3);
Visit(L1);
cout<<endl;
Visit(L2);
cout<<endl;
AddPolyn(L1,L2);
Visit(L1);
cout<<endl;
return 0;
}