#include<stdio.h>
#include<stdlib.h>
struct PolyNode{
int c;
int e;
struct PolyNode *next;
};
typedef struct PolyNode *Node;
Node Read();
Node Mult(Node P1,Node P2);
Node Add(Node P1,Node P2);
void Print(Node P);
void Attach(int c,int e,Node *P);
int main()
{
Node P1,P2;
Node PM,PA;
P1=Read();
P2=Read();
PM=Mult(P1,P2);
PA=Add(P1,P2);
Print(PM);
Print(PA);
return 0;
}
void Attach(int c,int e,Node *P)
{
Node New;
New=(Node)malloc(sizeof(struct PolyNode));
New->c = c;
New->e = e;
New->next = NULL;
(*P)->next = New;
*P=New;
}
Node Read()
{
int num,c,e;
scanf("%d",&num);
Node P,rear,t;
P=(Node)malloc(sizeof(struct PolyNode));
P->next=NULL;
rear=P;
while(num--)
{
scanf("%d %d",&c,&e);
Attach(c,e,&rear);
}
t=P;
P=P->next;
free(t);
return P;
}
Node Mult(Node P1,Node P2)
{
Node P,rear;
Node t1,t2,t;
int c,e;
t1=P1;
t2=P2;
P=(Node)malloc(sizeof(struct PolyNode));
P->next = NULL;
rear=P;
if(!P1||!P2)
return NULL;
while(t2)
{
Attach(t1->c*t2->c ,t1->e+t2->e ,&rear);
t2=t2->next;
}
while(t1)
{
rear=P;
t2=P2;
while(t2)
{
c=t1->c * t2->c;
e=t1->e + t2->e;
while(rear->e > e&&rear->e )
rear=rear->next;
if(rear->next->e == e&&rear->next)
{
if(rear->next->c+c)
rear->next->c +=c;
else
{
t=rear->next;
rear->next = t->next;
free(t);
}
}
else
{
t=(Node)malloc(sizeof(struct PolyNode));
t->c = c;
t->e = e;
t->next =rear->next;
rear->next=t;
rear=rear->next;
}
t2=t2->next;
}
t1=t1->next;
}
t1=P;
P=P->next;
free(t1);
return P;
}
Node Add(Node P1,Node P2)
{
Node P,t1,t2,rear;
int c,e;
t1=P1;
t2=P2;
P=(Node)malloc(sizeof(struct PolyNode));
P->next=NULL;
rear=P;
while(t1&&t2)
{
if(t1->e > t2->e)
{
Attach(t1->c,t1->e,&rear);
t1=t1->next;
}
else if(t1->e == t2->e )
{
if(t1->c+t2->c)
Attach(t1->c+t2->c,t1->e+t2->e,&rear);
t1=t1->next;
t2=t2->next;
}
else
{
Attach(t2->c,t2->e,&rear);
t2=t2->next;
}
}
while(t1)
{
Attach(t1->c,t1->e,&rear);
t1=t1->next;
}
while(t2)
{
Attach(t2->c,t2->e,&rear);
t2=t2->next;
}
t1=P;
P=P->next;
free(t1);
return P;
}
void Print(Node P)
{
Node t;
t=P;
if(t)
{
while(t)
{
if(t!=P)
printf(" ");
printf("%d %d",t->c,t->e);
}
printf("\n");
}
else
printf("0 0\n");
}
一元多项式的乘法与加法运算
最新推荐文章于 2022-05-09 12:23:30 发布