链表实现一元多项式的相乘

数据结构,同上,用c语言实现
2024-12-31 22:06:11
推荐回答(3个)
回答1:

写好了,你试试看
输入方法:
1 2 1 1 0 0
1 2 1 1 0 0

#include
#include
#include

typedef struct polynomial
{
int coef,ex;
struct polynomial *next;
}POLY;

POLY *create_poly(void);

POLY *add_poly(POLY *,POLY *);

POLY *mul_poly(POLY *,POLY *);

void print_poly(POLY *);

int main(void)
{
POLY *heada=NULL,*headb=NULL,*headsum=NULL,*headmul=NULL;
printf("create the first multinomial:\n");
heada=create_poly();
printf("create the second multinomial:\n");
headb=create_poly();
printf("The first multinomial:\n");
print_poly(heada);
printf("The second multinomial:\n");
print_poly(headb);
headsum=add_poly(heada,headb);
printf("The sum multinomial:");
print_poly(headsum);
headmul=mul_poly(heada, headb);
printf("The mul multinomial:");
print_poly(headmul);
return 0;
}

//创建
POLY *create_poly()
{
int iA=0,iE=0;
POLY *head=NULL,*s=NULL,*r=NULL;
head=(POLY *)malloc(sizeof(POLY));
r=head;
printf("please input coef and exponent:\n");
scanf("%d%d",&iA,&iE);
while(iA != 0)
{
s=(POLY *)malloc(sizeof(POLY));
s->coef=iA,s->ex=iE;
r->next=s;
r=s;
scanf("%d%d",&iA,&iE);
}
r->next=NULL;
return head;
}

//相加
POLY *add_poly(POLY *p1, POLY *p2) //多项式相加

{

POLY *head, *tmp, *s;

int value;

p1=p1->next;

p2=p2->next;

head=tmp=(POLY*)malloc(sizeof(POLY));

head->next=NULL;

while(p1 && p2)

{

if(p1->ex == p2->ex)

{

value=p1->coef+p2->coef;

if(value != 0)

{

s=(POLY *)malloc(sizeof(POLY));

s->coef=value;

s->ex=p1->ex;

s->next=NULL;

}

p1=p1->next;

p2=p2->next;

}

else

if(p1->ex < p2->ex)

{

s=(POLY *)malloc(sizeof(POLY));

s->coef=p1->coef;

s->ex=p1->ex;

s->next=NULL;

p1=p1->next;

}

else

{

s=(POLY *)malloc(sizeof(POLY));

s->coef=p2->coef;

s->ex=p2->ex;

s->next=NULL;

p2=p2->next;

}

if(head->next==NULL)

{

head->next=s;

tmp=s;

}

else

{

tmp->next=s;

tmp=s;

}

}

tmp->next=p1?p1:p2;

return head;

}

//相乘
POLY *mul_poly(POLY *p1, POLY *p2)

{

POLY *head;

POLY *t,*q,*s,*r;

head=(POLY *)malloc(sizeof(POLY));

head->next=NULL;

r=(POLY *)malloc(sizeof(POLY));

r->next=NULL;

for(t=p1->next;t;t=t->next)

{

for(q=p2->next;q;q=q->next)

{

s=(POLY *)malloc(sizeof(POLY));

r->next=s;

s->coef=q->coef * t->coef;

s->ex=q->ex + t->ex;

s->next=NULL;

head=add_poly(r,head);

}

}

return head;

}

//输出
void print_poly(POLY *head)
{
POLY *p=NULL;
p=head->next;
if(p == NULL)
printf("The multinomial is NULL.\n");
else
{
do
{
if(p->coef>=0)
printf("+%dx^%d",p->coef,p->ex);
else
printf("%dx^%d",p->coef,p->ex);
p=p->next;
}while(p != NULL);
printf("\n");
}
}

回答2:

没有那么多时间写啊 我可以告诉你思路 一起讨论一下

回答3:

pojplkm