#include<stdio.h>
#include<malloc.h>
typedef struct poly
{
float coef;
int exp;
struct poly *next;
}polynode;
polynode *blist(polynode *list)
{
polynode *q=list,*p;
float c;
int n,finish=0;
while(finish)
{
p=(polynode *)malloc(sizeof(polynode));
printf("请依次输入多项式的每一项的系数和指数:(升序)");
scanf("%f,%d",&c,&n);
p->coef=c;
p->exp=n;
q->next=p;
q=q->next;
printf("是否继续输入(是,请按1;否,请按0)");
scanf("%d",&finish);
}
return list;
}
polynode *polyadd(polynode *l1,polynode *l2)
{
polynode *head,*ha,*p=l1->next,*q=l2->next;
head=ha=(polynode *)malloc(sizeof(polynode));
while(p&&q)
{
if(p->exp<q->exp)
{
ha->next=p;
p=p->next;
}
else if(p->exp>q->exp)
{
ha->next=q;
q=q->next;
}
else
{
p->coef=p->coef+q->coef;
ha->next=p;
p=p->next;
free(q);
q=q->next;
}
ha=ha->next;
}
if(!p&&!q)
ha->next=NULL;
else if(!p)
ha->next=q;
else if(!q)
ha->next=p;
return head;
}
void main()
{
polynode *list[3],*p;
int i;
for(i=0;i<3;i++)
list[i]=(polynode *)malloc(sizeof(polynode));
blist(list[1]);
blist(list[2]);
list[3]=polyadd(list[1],list[2]);
p=list[3]->next;
while(p)
{
printf("%.2fX^%d",p->coef,p->exp);
p=p->next;
}
}
#include<malloc.h>
typedef struct poly
{
float coef;
int exp;
struct poly *next;
}polynode;
polynode *blist(polynode *list)
{
polynode *q=list,*p;
float c;
int n,finish=0;
while(finish)
{
p=(polynode *)malloc(sizeof(polynode));
printf("请依次输入多项式的每一项的系数和指数:(升序)");
scanf("%f,%d",&c,&n);
p->coef=c;
p->exp=n;
q->next=p;
q=q->next;
printf("是否继续输入(是,请按1;否,请按0)");
scanf("%d",&finish);
}
return list;
}
polynode *polyadd(polynode *l1,polynode *l2)
{
polynode *head,*ha,*p=l1->next,*q=l2->next;
head=ha=(polynode *)malloc(sizeof(polynode));
while(p&&q)
{
if(p->exp<q->exp)
{
ha->next=p;
p=p->next;
}
else if(p->exp>q->exp)
{
ha->next=q;
q=q->next;
}
else
{
p->coef=p->coef+q->coef;
ha->next=p;
p=p->next;
free(q);
q=q->next;
}
ha=ha->next;
}
if(!p&&!q)
ha->next=NULL;
else if(!p)
ha->next=q;
else if(!q)
ha->next=p;
return head;
}
void main()
{
polynode *list[3],*p;
int i;
for(i=0;i<3;i++)
list[i]=(polynode *)malloc(sizeof(polynode));
blist(list[1]);
blist(list[2]);
list[3]=polyadd(list[1],list[2]);
p=list[3]->next;
while(p)
{
printf("%.2fX^%d",p->coef,p->exp);
p=p->next;
}
}