#include<stdio.h>
#include<stdlib.h>
struct list{
float coef;
int expn;
struct list *nextptr;
};
typedef struct list polynomial;
typedef polynomial *P;
void addC(P *,int ,int);
void creatpolyn(P *,P*);
void add(P *);
void print(P*);
void mutiply(P*,P*,P*);
main()
{
P a,b,c;
c=NULL;
// printf("");
creatpolyn(&a,&b);
print(&a); print(&b);
mutiply(&a,&b,&c);
print(&c);
}
void creatpolyn(P * aptr,P * bptr)
{
P * ahead, * bhead;
ahead= aptr;
bhead= bptr;
printf("please input polynomials a\n");
add( aptr);
printf("please input polynomials b\n");
add(bptr);
aptr=ahead;
bptr=bhead;
}
void add(P * ptr)
{
int coef1,expn1;
P newptr,ptr1;
while (1) {
newptr=(P)malloc(sizeof(P));
if (!newptr) {
newptr->nextptr=NULL;
printf("please input coef and expn,when expn=9999,exit\n");
scanf("%d%d",&coef1,&expn1);
if (expn1==9999)
break;
newptr->coef=coef1;
newptr->expn=expn1;
ptr1=*ptr; //不能直接调用ptr->nextptr;
ptr1->nextptr= newptr;
ptr1=ptr1->nextptr;
}
}
}
void mutiply(P *ap,P *bp,P *cp)
{
int expn1,coef1;
P ahead,bhead,ap1,bp1,cp1;
ahead= *ap;
bhead=*bp;
ap1=*ap;
bp1=*bp;
cp1=*cp;
while (ap1&&bp1) {
expn1=ap1->expn+bp1->expn;
coef1=(ap1->coef) *( bp1->coef);
addC(&cp1,expn1,coef1);
if (bp1)
bp1=bp1->nextptr;
else if ((!bp1)&&(!ap1)) {
ap1=ahead;
bp1=bhead;
}
else if (!bp1) {
bp1=bhead;
ap1=ap1->nextptr;
}
/* else if (bp1&&ap1) {
ap1=ahead;
bp1=bhead;
}
*/
/* if (ap)
cp->nextptr=bp;
else if (bp)
cp->nextptr=ap;
if (ap->expn>bp->expn)
bp=bp->nextptr;
else if (ap->expn<bp->expn)
ap=ap->nextptr;}}
*/
}
void addC(P * c,int expn2,int coef2)
{
P chead,newptr,pre,c1;
chead=*c;
c1=*c;
while (c1) {
pre=c1;
if (c1->expn==expn2)
c1->coef=coef2;
else c1=c1->nextptr;
}
c1=pre;
newptr=(P)malloc(sizeof(P));
if (!newptr) {
newptr->nextptr=NULL;
newptr->coef=coef2;
newptr->expn=expn2;
c1->nextptr=newptr;
}
}