#include <stdio.h>
#include <stdlib.h>
typedef struct PolyNode* polynomial;
typedef struct PolyNode{
int expon;
int coef;
polynomial link;
}PolyNode;
polynomial ReadPoly();
void PrintPoly(polynomial P);
void Attach(int c, int e, polynomial * pRear);
polynomial Mult(polynomial P1, polynomial P2);
polynomial Add(polynomial P1, polynomial P2);
int main(){
polynomial P1,P2;
polynomial PP,PS;
P1=ReadPoly();
P2=ReadPoly();
PP=Mult(P1,P2);
PrintPoly(PP);
PS=Add(P1,P2);
PrintPoly(PS);
/*PrintPoly(P1);
PrintPoly(P2);*/
return 0;
}
polynomial Add(polynomial p1,polynomial p2){
int c,e,coeftmp;
polynomial Rear,temp;
polynomial t1=p1,t2=p2;
polynomial P=(polynomial)malloc(sizeof(PolyNode));
P->link=NULL;
Rear=P;
while(t1&&t2){
if(t1->expon>t2->expon){
c=t1->coef;
e=t1->expon;
Attach(c,e,&Rear);
t1=t1->link;
}
else if (t1->expon < t2->expon)
{
//新建结点存储当前t2,插入到链表尾
c = t2->coef;
e = t2->expon;
Attach(c, e,& Rear);
t2 = t2->link;
}
//t1系数等于t2系数
else
{
coeftmp = t1->coef + t2->coef;
//若系数不为0,则创建结点
if (coeftmp != 0)
{
c = coeftmp;
e = t2->expon;
Attach(c, e, &Rear);
}
//向下遍历
t1 = t1->link;
t2 = t2->link;
}
}
while (t1)
{
c = t1->coef;
e = t1->expon;
Attach(c, e, &Rear);
t1 = t1->link;
}
while (t2)
{
c = t2->coef;
e = t2->expon;
Attach(c, e,& Rear);
t2 = t2->link;
}
return P->link;
}
void Attach(int c,int e,polynomial * pRear){
polynomial p;
p=(polynomial)malloc(sizeof(PolyNode));
p->coef=c;
p->expon=e;
p->link=NULL;
(*pRear)->link=p;
(*pRear)=p;
}
polynomial ReadPoly()
{
polynomial P1 = (polynomial)malloc(sizeof(PolyNode));
polynomial Rear = P1;
int N, c, e;
scanf("%d ", &N);
while (N--)
{
scanf("%d %d", &c, &e);
Attach(c, e, &Rear);
}
polynomial tmp = P1;
P1 = P1->link;
free(tmp);
return P1;
}
void PrintPoly(polynomial P)
{
int flag = 0;
if (!P)
{
printf("0 0\n");
return ;
}
while (P)
{
if(flag==1)
printf(" ");
printf("%d %d", P->coef, P->expon);
P = P->link;
flag=1;
}
printf("\n");
}
polynomial Mult(polynomial p1,polynomial p2){
if(!p1||!p2)return NULL;
int c,e,ctmp,etmp;
polynomial t1=p1,t2=p2,Rear,Rearbef,tmp;
polynomial P=(polynomial)malloc(sizeof(PolyNode));
int flag=0;
P->link=NULL;
Rear=P;
while(t2){//初始化结果链表
c = t1->coef * t2->coef;
e = t1->expon + t2->expon;
Attach(c, e,& Rear);
t2 = t2->link;
}
t1=t1->link;
while(t1){
c = t1->coef;
e = t1->expon;
t2 = p2;
while(t2){
ctmp=c*(t2->coef);
etmp=e+(t2->expon);
Rear=P->link;
Rearbef=P;
while(Rear)
{
if(Rear->expon==etmp){
ctmp+=(Rear->coef);
if(ctmp!=0){
Rear->coef=ctmp;
t2=t2->link;
break;
}
else{
tmp=Rear;
Rearbef->link=Rear->link;
free(tmp);
t2=t2->link;
break;
}
}
else if(Rear->expon>etmp){
Rearbef=Rear;
Rear=Rear->link;
}
else{
polynomial x = (polynomial)malloc(sizeof(PolyNode));
x->coef = ctmp;
x->expon = etmp;
x->link = Rear;
Rearbef->link = x;
t2 = t2->link;
break;
}
}
if(Rear==NULL){
polynomial x = (polynomial)malloc(sizeof(PolyNode));
x->coef = ctmp;
x->expon = etmp;
x->link = NULL;
Rearbef->link = x;
t2 = t2->link;
}
}
t1=t1->link;
}
return P->link;
}
/*4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1*/