设计函数分别求两个一元多项式的乘积与和。
输入分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
1.注意新建链表完成后删除空的头结点;
2.按照指数递降的格式输入输出多项式;
3.多项式乘法可通过加法实现。
C语言代码:
#include
#include
typedef int ElementType;
typedef struct Node*PtrToNode;
typedef PtrToNode List;
struct Node{
ElementType coef;
ElementType expon;
PtrToNode Next;
};
List Read();
void Print(List L);
void Attach(int c,int e,List *pRear);
List Add(List L1,List L2);
List Mult(List L1,List L2);
int main()
{
List L1,L2,LMult,LAdd;
L1 = Read();
L2 = Read();
LMult=Mult(L1,L2);
Print(LMult);
LAdd=Add(L1,L2);
Print(LAdd);
return 0;
}
List Read()
{
List L,Rear,t;
int c,e,N;
scanf("%d",&N);//输入多项式项数
L=(List)malloc(sizeof(struct Node));
L->Next=NULL;//尾指针初始值为NULL
Rear=L;
while(N--)
{
scanf("%d %d",&c,&e);
Attach(c,e,&Rear);
}
t=L;L=L->Next;free(t);//释放空的头结点
return L;
}
void Attach(int c,int e,List *pRear)//链接一个单独项
{
List P;//指向临时存放的新项
P=(List)malloc(sizeof(struct Node));
P->coef=c;
P->expon=e;
P->Next=NULL;
(*pRear)->Next=P;//将P连接至 链表尾
*pRear=P;//Rear移至新的链表尾
}
List Add(List L1,List L2)//多项式加法
{
List t1,t2,L,Rear;
List t,p;
t1=L1;t2=L2;
L=(List)malloc(sizeof(struct Node));
L->Next=NULL;
Rear=L;
while(t1&&t2)//t1 t2都不空
{
if(t1->expon==t2->expon)//指数相等,系数相加
{
if(t1->coef+t2->coef)//系数此相加不为零
Attach(t1->coef+t2->coef,t1->expon,&Rear);
t1=t1->Next;
t2=t2->Next;
}
else if(t1->expon>t2->expon)//第一个多项式当前项指数大于第二个,则插入
{
Attach(t1->coef,t1->expon,&Rear);
t1=t1->Next;
}
else
{
Attach(t2->coef,t2->expon,&Rear);
t2 = t2->Next;
}
}
Rear->Next=t1?t1:t2;//将非空多项式的剩余项链接L后
Rear=Rear->Next;
p=L;L=L->Next;free(p);
return L;
}
List Mult(List L1,List L2)//多项式乘法
{
List MultByNode(struct Node L1, List L2);
List L,temp,t1,t2,Rear;
t1=L1;t2=L2;
if(!t1||!t2)//其中有一个是零多项式,相乘结果为零
return NULL;
else
{
L=MultByNode(*t1,L2);//第一个多项式的第一项乘以第二个多项式,得到初始结果
t1=t1->Next;
while(t1)
{
temp=MultByNode(*t1,L2);//第一个多项式后面每一项乘以第二个多项式
L=Add(L,temp);// 并做加法运算
t1=t1->Next;
}
return L;
}
}
List MultByNode(struct Node L1,List L2)
{
List Rear,L,t2;
L=(List)malloc(sizeof(struct Node));
L->Next=NULL;
Rear=L;
t2=L2;
int c,e;
while(t2)
{
c=L1.coef*t2->coef;e=L1.expon+(*t2).expon;//注意L1,t2以及它们的类型
Attach(c,e,&Rear);
t2=t2->Next;
}
List t=L;L=L->Next;free(t);
return L;
}
void Print( List L ) //输出格式为c1 e1 c2 e2...
{
int flag=0;
if(!L)
{
printf("0 0\n");
return;
}
while(L)
{
if(!flag)//第一项前面不输出空格
flag=1;
else
printf(" ");
printf("%d %d",L->coef,L->expon);
L=L->Next;
}
printf("\n");
}