#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(node)
typedef struct polynode{
int coef;//系数
int exp; //指数
struct polynode *link;
}node;
node *create()//创建多项式
{
node *p,*r,*h,*s;
h=(node *)malloc(LEN);
r=h;
int coef;
int exp;
scanf("%d",&coef);//输入系数
scanf("%d",&exp);//输入指数
while(coef)
{
p=(node *)malloc(LEN);
p->coef=coef;
p->exp=exp;
h->link=p;
h=p;
scanf("%d",&coef);//输入系数
scanf("%d",&exp);//输入指数
}
h->link=NULL;
s=r;
r=r->link;
free(s);
return r;
}
void attach(int coef,int exp,node *rear)
{
node *temp;
temp=(node *)malloc(LEN);
temp->coef=coef;
temp->exp=exp;
rear->link=temp;
rear=temp;
}
node *addpoly(node *p,node *q)
{
int sum;
node *r,*t,*s,*w;
r=(node *)malloc(LEN);
t=r;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
attach(q->coef,q->exp,r);
q=q->link;
}
else if(p->exp>q->exp)
{
attach(p->coef,p->exp,r);
p=p->link;
}
else
{
sum=p->coef+q->coef;
if(sum)
{
w=(node *)malloc(LEN);
w->coef=sum;
w->exp=p->exp;
attach(w->coef,w->exp,r);
}
p=p->link;
q=q->link;
}
}
for(;p;p=p->link)
{
attach(p->coef,p->exp,r);
}
for(;q;q=q->link)
{
attach(q->coef,q->exp,r);
}
r->link=NULL;
s=t;
t=t->link;
free(s);
return t;
}
main()
{
node *a,*b,*z;
printf("请输入第一个多项式的系数与指数:");
a=create();
printf("请输入第二个多项式的系数与指数:");
b=create();
z=addpoly(a,b);
while(z->link)
{
printf("%dx^%d+",z->coef,z->exp);
z=z->link;
}
printf("%dx^%d\n",z->coef,z->exp);
return 0;
}
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(node)
typedef struct polynode{
int coef;//系数
int exp; //指数
struct polynode *link;
}node;
node *create()//创建多项式
{
node *p,*r,*h,*s;
h=(node *)malloc(LEN);
r=h;
int coef;
int exp;
scanf("%d",&coef);//输入系数
scanf("%d",&exp);//输入指数
while(coef)
{
p=(node *)malloc(LEN);
p->coef=coef;
p->exp=exp;
h->link=p;
h=p;
scanf("%d",&coef);//输入系数
scanf("%d",&exp);//输入指数
}
h->link=NULL;
s=r;
r=r->link;
free(s);
return r;
}
void attach(int coef,int exp,node *rear)
{
node *temp;
temp=(node *)malloc(LEN);
temp->coef=coef;
temp->exp=exp;
rear->link=temp;
rear=temp;
}
node *addpoly(node *p,node *q)
{
int sum;
node *r,*t,*s,*w;
r=(node *)malloc(LEN);
t=r;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
attach(q->coef,q->exp,r);
q=q->link;
}
else if(p->exp>q->exp)
{
attach(p->coef,p->exp,r);
p=p->link;
}
else
{
sum=p->coef+q->coef;
if(sum)
{
w=(node *)malloc(LEN);
w->coef=sum;
w->exp=p->exp;
attach(w->coef,w->exp,r);
}
p=p->link;
q=q->link;
}
}
for(;p;p=p->link)
{
attach(p->coef,p->exp,r);
}
for(;q;q=q->link)
{
attach(q->coef,q->exp,r);
}
r->link=NULL;
s=t;
t=t->link;
free(s);
return t;
}
main()
{
node *a,*b,*z;
printf("请输入第一个多项式的系数与指数:");
a=create();
printf("请输入第二个多项式的系数与指数:");
b=create();
z=addpoly(a,b);
while(z->link)
{
printf("%dx^%d+",z->coef,z->exp);
z=z->link;
}
printf("%dx^%d\n",z->coef,z->exp);
return 0;
}