weixin_38517428
weixin_38517428
2018-02-13 15:04

请问下题C语言实现多项式乘法的代码中存在的错误,加法是正确的输出,乘法为何结果总是错误,本人不胜感激

10
  • c

#include
#include
typedef int elemType;

typedef struct Node{
elemType Coefficient;
elemType Exponent;
struct Node *next;
}Node,*LinkedList;

int empty(LinkedList L);
LinkedList LinkedCreatT(int n);
LinkedList add_list(LinkedList a,LinkedList b);
LinkedList multi_list(LinkedList a,LinkedList b);
void show(LinkedList L);

int main()
{
LinkedList m,n,ans;
printf("输入第一个多项式\n");
m=LinkedCreatT(2);
show(m);
printf("\n");
printf("输入第二个多项式\n");
n=LinkedCreatT(2);
show(n);
printf("\n");
printf("他们的积是\n");
ans= multi_list(m,n);
show(ans);
return 0;
}

int empty(LinkedList L)
{
return L->next==NULL;
}

LinkedList LinkedCreatT(int n)
{
Node *L;
L=(Node *)malloc(sizeof(Node));
L->next=NULL;
Node *r;
r=L;
int k=n;
while(n--)
{
printf("请输入第%d项\n",k-n);
elemType coe,exp;
scanf("%d%d",&coe,&exp);
Node *p;
p=(Node *)malloc(sizeof(Node));
p->Coefficient=coe;
p->Exponent=exp;
r->next=p;
r=p;
}
r->next=NULL;
return L->next;
}

LinkedList add_list(LinkedList a,LinkedList b)
{
Node *L;
L=(Node *)malloc(sizeof(Node));
L->next=NULL;
Node *r;
r=L;
while(a&&b)
{
Node *p;
p=(Node *)malloc(sizeof(Node));
if(a->Exponent>b->Exponent)
{
p->Exponent=a->Exponent;
p->Coefficient=a->Coefficient;
a=a->next;
r->next=p;
r=p;
}
else if(a->ExponentExponent)
{
p->Exponent=b->Exponent;
p->Coefficient=b->Coefficient;
b=b->next;
r->next=p;
r=p;
}
else
{
if((a->Coefficient+b->Coefficient)!=0)
{
p->Coefficient=a->Coefficient+b->Coefficient;
p->Exponent=b->Exponent;
r->next=p;
r=p;
}
a=a->next;
b=b->next;
}
}
if(a)
r->next=a;
else
r->next=b;
return L->next;
}

LinkedList multi_list(LinkedList a,LinkedList b)
{
Node *L;
L=(Node *)malloc(sizeof(Node));
L->next=NULL;
while(a)
{
Node *t;
t=(Node *)malloc(sizeof(Node));
t->next=NULL;
Node *r;
r=t;
while(b)
{
Node *p;
p=(Node *)malloc(sizeof(Node));
p->Coefficient=b->Coefficient*a->Coefficient;
p->Exponent=b->Exponent+a->Exponent;
r->next=p;
r=p;
b=b->next;
}
r->next=NULL;

    a=a->next;
    printf("多项式当前是\n");
    show(L->next);
    printf("新链是\n");
    show(t->next);

    L->next=add_list(L->next,t->next);
    printf("多项式变为\n");
    show(L->next);
}
return L->next;

}
void show(LinkedList L)
{
int i=1;
while(L)
{
printf("该多项式是%d 乘x的%d次方\n",L->Coefficient,L->Exponent);
L=L->next;
}
}

本人的问题主要是在例如乘法中(a+b)*(c+d),表示c乘(a+b)的链表能正常返回,但永远只能返回这一项,之后的项数不能返回,通过查看打印结果发现除第一次以外之后的t链表永远为空。谢谢各位大神的赐教

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答