一元多項式的乘法和加法用帶頭結點的單鏈表的C語言實現
設計函數分別求兩個一元多項式的乘積與和。
輸入格式:
輸入分2行,每行分別先給出多項式非零項的個數,再以指數遞降方式輸入一個多項式非零項係數和指數(絕對值均爲不超過1000的整數)。數字間以空格分隔。
輸出格式:
輸出分2行,分別以指數遞降方式輸出乘積多項式以及和多項式非零項的係數和指數。數字間以空格分隔,但結尾不能有多餘空格。零多項式應輸出0 0。
輸入樣例:
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;
}Lnode,*LinkList;
LinkList CreatListR(int n);
void Disp(LinkList L);
LinkList Addition(LinkList L1,LinkList L2);
LinkList Multiply(LinkList L1,LinkList L2);
void Attach(int c,int e,LinkList *r);
LinkList CreatListR(int n)
{
LinkList L,s,p;
L=(LinkList)malloc(sizeof(Lnode));
L->next=NULL;
p=L;
int i;
for (i=0;i<n;i++)
{
s=(LinkList)malloc(sizeof(Lnode));
scanf(" %d %d",&s->coef,&s->expon);
p->next=s;
p=s;
}
p->next=NULL;
return L;
}
void Disp(LinkList L)
{
LinkList p;
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);
}
LinkList Addition(LinkList L1,LinkList L2)
{
LinkList front,rear;
front=(LinkList)malloc(sizeof(Lnode));
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;
}
LinkList Multiply(LinkList L1,LinkList L2)
{
LinkList front,rear,t1,t2;
front=(LinkList)malloc(sizeof(Lnode));
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
{
LinkList t=(LinkList)malloc(sizeof(Lnode));
t->coef=c;
t->expon=e;
t->next=rear->next;
rear->next=t;
rear=t;
}
t2=t2->next;
}
t1=t1->next;
}
return front;
}
void Attach(int c,int e,LinkList *r)
{
LinkList p;
p=(LinkList)malloc(sizeof(Lnode));
p->coef=c;
p->expon=e;
p->next=NULL;
(*r)->next=p;
*r=p;
}
int main()
{
int n1,n2;
LinkList L2,L1,L11,L22;
scanf(" %d",&n1);
L1=CreatListR(n1);
scanf(" %d",&n2);
L2=CreatListR(n2);
L22=Multiply(L1,L2);
L11=Addition(L1,L2);
Disp(L22);
Disp(L11);
return 0;
}