一元多项式的乘法与加法运算 (20 分)
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
#include<stdio.h>
#include<stdlib.h>
typedef struct poly *List;
struct poly{
int x;
int z;
List next;
};
List read();
List sum(List A,List B);
List cheng(List A,List B);
void print(List P);
int main(){
List A,B,h,g;
A=read();
B=read();
h=sum(A,B);
g=cheng(A,B);
print(g);
print(h);
return 0;
}
List read(){
int n;
List s;
s=(List)malloc(sizeof(struct poly));
s->next=NULL;
scanf("%d",&n);
if(n){
List m=s;
int i;
for(i=0;i<n;i++){
List p=(List)malloc(sizeof(struct poly));
scanf("%d%d",&(p->x),&(p->z));
m->next=p;
m=p;
}
m->next=NULL;
}
return s;
}
List sum(List A,List B){
List pa,pb,pc,L;
L = (List)malloc(sizeof(struct poly));
L->next=NULL;
pa=A->next;
pb=B->next;
pc = L;
while(pa && pb)
{
if(pa->z<pb->z){
List temp=(List)malloc(sizeof(struct poly));
temp->next=NULL;
temp->x=pb->x;
temp->z=pb->z;
pc->next=temp;
pc=temp;
pb=pb->next;
}
else if(pa->z==pb->z){
int a=pa->x+pb->x;
if(a!=0){
List temp=(List)malloc(sizeof(struct poly));
temp->next=NULL;
temp->z=pa->z;
temp->x=a;
pc->next=temp;
pc=temp;
}
pb=pb->next;
pa=pa->next;
}
else{
List temp=(List)malloc(sizeof(struct poly));
temp->next=NULL;
temp->x=pa->x;
temp->z=pa->z;
pc->next=temp;
pc=temp;
pa=pa->next;
}
}
if(pa){
while(pa){
List temp=(List)malloc(sizeof(struct poly));
temp->next=NULL;
temp->x=pa->x;
temp->z=pa->z;
pc->next=temp;
pc=temp;
pa=pa->next;
}
}
else{
while(pb){
List temp=(List)malloc(sizeof(struct poly));
temp->x=pb->x;
temp->z=pb->z;
pc->next=temp;
pc=temp;
pb=pb->next;
}
}
pc->next=NULL;
return L;
}
List cheng(List A,List B){
List p1,p2,p3,L,Lm;
L=(List)malloc(sizeof(struct poly));
p1=A->next;
p2=B->next;
L->next=NULL;
if(p1&&p2){
for(p1=A->next;p1;p1=p1->next){
Lm=(List)malloc(sizeof(struct poly));
Lm->next=NULL;
p3=Lm;
for(p2=B->next;p2;p2=p2->next){
List p4=(List)malloc(sizeof(struct poly));//尾插法
p4->x=p1->x*p2->x;
p4->z=p1->z+p2->z;
p3->next=p4;
p3=p4;
}
p3->next=NULL;//若不写,则内存出错
L=sum(L,Lm);
free(Lm);
}
}
return L;
}
void print(List P){
List t;
int i=0;
if(P->next==NULL){
printf("0 0");
}
else{
for(t=P->next;t;t=t->next){
if(i==0) printf("%d %d",t->x,t->z);
else printf(" %d %d",t->x,t->z);
i++;
}
}
printf("\n");
}