# 一元多項式的乘法和加法用帶頭結點的單鏈表的C語言實現

## 一元多項式的乘法和加法用帶頭結點的單鏈表的C語言實現

4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

``````#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef int Elemtype;
typedef struct Lnode
{
Elemtype coef;
Elemtype expon;
struct Lnode *next;

{
L->next=NULL;
p=L;
int i;
for (i=0;i<n;i++)
{
scanf(" %d %d",&s->coef,&s->expon);
p->next=s;
p=s;
}
p->next=NULL;
return L;
}

{
if (!L->next)
{
printf("0 0\n");
return;
}
p=L->next;
while(p->next&&p)
{
printf("%d %d ",p->coef,p->expon);
p=p->next;
}
printf("%d %d\n",p->coef,p->expon);
}

{
front->next=NULL;
rear=front;
L1=L1->next;
L2=L2->next;
int sum,a;
while(L1&&L2)
{
if(L1->expon<L2->expon) a=-1;
if(L1->expon>L2->expon) a=1;
if(L1->expon==L2->expon) a=0;
switch(a)
{
case -1:
Attach(L2->coef,L2->expon,&rear);
L2=L2->next;
break;
case 1:
Attach(L1->coef,L1->expon,&rear);
L1=L1->next;
break;
default:
sum=L1->coef+L2->coef;
if(sum) Attach(sum,L1->expon,&rear);
L1=L1->next;
L2=L2->next;
break;
}
}
for(;L1;L1=L1->next) Attach(L1->coef,L1->expon,&rear);
for(;L2;L2=L2->next) Attach(L2->coef,L2->expon,&rear);
return front;
}

{
front->next=NULL;
rear=front;
if (!L1->next||!L2->next) return front;
t1=L1->next;t2=L2->next;
while(t2)
{
Attach(t1->coef*t2->coef,t1->expon+t2->expon,&rear);
t2=t2->next;
}
t1=t1->next;
while(t1)
{
t2=L2->next;
rear=front;
while(t2)
{
int c,e;
c=t1->coef*t2->coef;
e=t1->expon+t2->expon;
while(rear->next&&rear->next->expon>e) rear=rear->next;
if(rear->next&&rear->next->expon==e)
{
if(rear->next->coef+c) rear->next->coef+=c;
else
{
rear->next->coef=0;
rear->next->expon=0;
}
}
else
{
t->coef=c;
t->expon=e;
t->next=rear->next;
rear->next=t;
rear=t;
}
t2=t2->next;
}
t1=t1->next;
}
return front;
}

{
p->coef=c;
p->expon=e;
p->next=NULL;
(*r)->next=p;
*r=p;
}

int main()
{
int n1,n2;
scanf(" %d",&n1);
L1=CreatListR(n1);
scanf(" %d",&n2);
L2=CreatListR(n2);
L22=Multiply(L1,L2);