数据结构之一元多项式相乘

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cowoc1961331326/article/details/71125181
#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
int coef;
int expn;
struct Node *next;
}List;
List *Creat()
{
List *head,*p1,*p2;
p1=p2=(List *)malloc(sizeof(List));
head=NULL;
scanf("%d%d",&p1->coef,&p1->expn);
p1->next=NULL;
while(p1->coef!=-1&&p1->expn!=-1)
{
if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
p1=(List *)malloc(sizeof(List));
scanf("%d%d",&p1->coef,&p1->expn);
}
p2->next=NULL;
return head;
}
List *Multi(List *head1,List *head2)
{
List *p1,*p2,*p3,*p4;
List *head;
p1=head1;
p2=head2;
p3=p4=(List *)malloc(sizeof(List));
head=p3;
p3->next=NULL;
while(p1)
{
while(p2)
{
p3->coef=p1->coef*p2->coef;
p3->expn=p1->expn+p2->expn;
p2=p2->next;
p4=p3;
p3=(List *)malloc(sizeof(List));
p4->next=p3;
}
p2=head2;
p1=p1->next;
}
p4->next=NULL;
return head;
}
List *Sort(List *head)
{
List *p1,*p2;
int coef,expn;
for(p1=head;p1!=NULL;p1=p1->next)
{
for(p2=p1->next;p2!=NULL;p2=p2->next)
{
if(p1->expn<p2->expn)
{
coef=p2->coef;
p2->coef=p1->coef;
p1->coef=coef;
expn=p2->expn;
p2->expn=p1->expn;
p1->expn=expn;
}
}
}
return head;
}
List *Merge(List *head)
{
List *p1,*p2,*p3;
p1=head;
while(p1)
{
p2=p1->next;
while(p2)
{
if(p1->expn==p2->expn)
{
p3=p2->next;
p1->coef+=p2->coef;
p1->next=p3;
free(p2);
}
p2=p2->next;
}
p1=p1->next;
}
return head;
}
void print(List *head)
{
List *p;
p=head;
while(p)
{
printf("%d %d ",p->coef,p->expn);
p=p->next;
}
printf("\n");
}
int main()
{
List *head1;
List *head2;
List *head3;
List *head4;
List *head5;
head1=Creat();
head2=Creat();
head3=Multi(head1,head2);
head4=Sort(head3);
head5=Merge(head4);
print(head5);
}

没有更多推荐了,返回首页