多項式相加程序代碼(C語言) ,供那些c語言初學者參考。
#i nclude<stdio.h>
#i nclude<malloc.h>
#i nclude<stdlib.h>
#define LEN sizeof(node)
typedef struct polynode
{
int coef;
int exp;
struct polynode *next;
}node;
node * create(void)
{
node *h,*r,*s;
int c,e;
h=(node *)malloc(LEN);
r=h;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
while(c!=0)
{
s=(node *)malloc(LEN);
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
}
r->next=NULL;
return(h);
}
polyadd(node *polya, node *polyb)
{
node *p,*q,*pre,*temp;
int sum;
p=polya->next;
q=polyb->next;
pre=polya;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
pre->next=p;pre=pre->next;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
pre->next=p;pre=pre->next;
p=p->next;temp=q;q=q->next;free(temp);
}
else
{temp=p->next;free(p);p=temp;
temp=q->next;free(q);q=temp;
}
}
else
{pre->next=q;pre=pre->next;
q=q->next;
}
}
if(p!=NULL)
pre->next=p;
else
pre->next=q;
}
void print(node * p)
{
while(p->next!=NULL)
{
p=p->next;
printf(" %d*x^%d",p->coef,p->exp);
}
}
main()
{
node * polya,* polyb;
printf("Welcome to use!\n");
printf("\nPlease input the ploya include coef && exp:\n");
polya=create();
print(polya);
printf("\nPlease input the ployb include coef && exp:\n");
polyb=create();
print(polyb);
printf("\nSum of the poly is:\n");
polyadd(polya,polyb);
print(polya);
printf("\n");
}