一元多项式的简单计算
输入两个一元多项式实现相加,相减。但运行结果没有将相同指数的系数合并,求大神找错误!!!#include<stdio.h>
#include<stdlib.h>
typedef struct Lnode
{
int coef; //系数
int exp; //指数
struct Lnode *next;
}Lnode,*LinkList;
//用尾插法建立一元多项式的链表
LinkList create()
{
LinkList h;
Lnode *r,*s;
int c;
int e;
h=(LinkList)malloc(sizeof(Lnode));
h->next=NULL;
r=h;
printf("输入系数:");
scanf("%d",&c);
printf("输入指数:");
scanf("%d",&e);
while(c!=0)
{
s=(Lnode*)malloc(sizeof(Lnode));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("输入系数:");
scanf("%d",&c);
printf("输入指数:");
scanf("%d",&e);
}
r->next=NULL;
return(h);
}
//多项式的输出
void print(LinkList h)
{
LinkList pre;
pre=h->next;
if(pre->exp==0)
printf("%d",pre->coef);
else printf("%d*x^%d",pre->coef,pre->exp);
pre=pre->next;
while(pre)
{
if(pre->exp==0)
{
if(pre->coef>0)
printf("+%d",pre->coef);
else printf("%d",pre->coef);
}
else
{
if(pre->coef>0)
printf("+%d*x^%d",pre->coef,pre->exp);
else printf("%d*x^%d",pre->coef,pre->exp);
}
pre=pre->next;
}
}
//两个多项式的加法
LinkList add(LinkList H1,LinkList H2)
{
LinkList H3,p1,p2,p3,pre;
H3=(LinkList)malloc(sizeof(Lnode));
H3->next=NULL;
p1=H1->next;
p2=H2->next;
pre=H3;
while(p1&&p2)
{
if(p1->exp>p2->exp)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=p1->coef;
p3->exp=p1->exp;
p3->next=pre->next;
pre->next=p3;
pre=p3;
p1=p1->next;
}
else if(p1->exp<p2->exp)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=p2->coef;
p3->exp=p2->exp;
p3->next=pre->next;
pre->next=p3;
pre=p3;
p2=p2->next;
}
else if(p1->coef+p2->coef!=0)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=p1->coef+p2->coef;
p3->exp=p1->exp;
p3->next=pre->next;
pre->next=p3;
pre=p3;
p1=p1->next;
p2=p2->next;
}
else
{
p1=p1->next;
p2=p2->next;
}
}
if(p2)
{
while(p2)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=p2->coef;
p3->exp=p2->exp;
p3->next=pre->next;
pre->next=p3;
pre=p3;
p2=p2->next;
}
}
else if(p1)
{
while(p1)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=p1->coef;
p3->exp=p1->exp;
p3->next=pre->next;
pre->next=p3;
pre=p3;
p1=p1->next;
}
}
if(H3->next==NULL)
{
p3=(LinkList)malloc(sizeof(Lnode));
p3->coef=0;
p3->exp=0;
p3->next=NULL;
H3->next=p3;
}
return H3;
}
//多项式的减法
LinkList substract(LinkList H1,LinkList H2)
{
LinkList H3,pre;
pre=H2->next;
while(pre)
{
pre->coef=(-1)*pre->coef;
pre=pre->next;
}
H3=add(H1,H2);
return H3;
}
void main()
{
LinkList head1,head2,head3,head4;
head1=create();
printf("表达式head1为:");
print(head1);
printf("\n");
head2=create();
printf("表达式head2为:");
print(head2);
printf("\n");
head3=add(head1,head2);
printf("表达式head3为:");
print(head3);
printf("\n");
head4=substract(head1,head2);
printf("表达式head4为:");
print(head4);
printf("\n");
}