#include "stdafx.h"
#include "stdlib.h"
typedef struct PolyNode *Polynomial;
struct PolyNode{ /*构造一个链表,包括多项式某一项的系数coef和指数expon,以及下一项的地址link*/
int coef;
int expon;
Polynomial link;
};
void Attach(int c,int e,Polynomial *pRear) /*把传递进来的c,e和*pRear存进申请的链表地址P内*/
{
Polynomial P;
P=(Polynomial)malloc(sizeof(struct PolyNode));
P->coef=c;
P->expon=e;
P->link=NULL;
(*pRear)->link=P;
*pRear=P;
}
Polynomial ReadPoly()
{
Polynomial P,Rear,t;
int c,e,N;
//printf("请输入多项式的项数:");
scanf("%d",&N);
P=(Polynomial)malloc(sizeof(struct PolyNode)); //此处先生成一个空的结构p,以便在后面插入正式结构,最后要free掉;
P->link=NULL;
Rear=P;
while(N--){
printf("请依次输入第%d项的系数和指数:",N+1);
scanf("%d %d",&c,&e);
Attach(c,e,&Rear);
}
t=P;
P=P->link;
free(t);
return P;
}
int Compare(int a,int b) /*该函数对P1和P2进行比较,比较结果传回switch函数里*/
{
if(a>b)
return 1;
else if(a<b)
return -1;
else
return 0;
}
Polynomial Add(Polynomial P1,Polynomial P2) /*多项式加法运算*/
{
Polynomial front,rear,temp;
int sum;
rear=(Polynomial)malloc(sizeof(PolyNode));
front=rear;
while(P1&&P2) /*当P1和P2都不为空时,对比P1和P2某一项的指数大小,指数大的先传进P里*/
{
switch(Compare(P1->expon,P2->expon)){
case 1: /*P1>P2*/
Attach(P1->coef,P1->expon,&rear);
P1=P1->link;
break;
case -1: /*P1<P2*/
Attach(P2->coef,P2->expon,&rear);
P2=P2->link;
break;
case 0: /*P1=P2*/
sum=P1->coef+P2->coef; /*判断这一项P1和P2的系数相加是不是等于0,不等于零就把结果传进P,等于零就不用处理,而P1和P2的表头都要往后传*/
if(sum)
Attach(sum,P1->expon,&rear);
P1=P1->link;
P2=P2->link;
break;
}
}
for(;P1;P1->link) /*加到P1或P2为空时,就把剩下非空的多项式的剩余项都加进P里*/
Attach(P1->coef,P1->expon,&rear);
for(;P2;P2->link)
Attach(P2->coef,P2->expon,&rear);
rear->link=NULL;
temp=front;
front=front->link;
free(temp);
return front;
}
Polynomial Mult(Polynomial P1,Polynomial P2) /*多项式相乘,这里用的是插入法,先用P1的第一项乘以P2的每一项,构造一个链表P,然后再用P1剩余的项乘以P2的每一项,乘积再插入到P中*/
{
Polynomial P,Rear,t1,t2,t;
int c,e;
if(!P1||!P2)
return NULL;
t1=P1;
t2=P2;
P=(Polynomial)malloc(sizeof(struct PolyNode)); /*构造空表头*/
P->link=NULL;
Rear=P; /*Rear为链表P的表尾*/
while(t2){ /*先用P1的第1项乘以P2,得到P*/
Attach(t1->coef*t2->coef,t1->expon+t2->expon,&Rear);
t2=t2->link;
}
t1=t1->link;
while(t1){
t2=P2;
Rear=P;
while(t2){
e=t1->expon+t2->expon;
c=t1->coef*t2->coef;
while(Rear->link&&Rear->link->expon>e)
Rear=Rear->link;
if(Rear->link&&Rear->link->expon==e){
if(Rear->link->coef+c)
Rear->link->coef+=c;
else{
t=Rear->link;
Rear->link=t->link;
free(t);
}
}
else{
t=(Polynomial)malloc(sizeof(struct PolyNode));
t->coef=c;
t->expon=e;
t->link=Rear->link;
Rear->link=t;Rear=Rear->link;
}
t2=t2->link;
}
t1=t1->link;
}
t2=P;
P=P->link;
free(t2);
return P;
}
void PrintPoly(Polynomial P)
{/*输出多项式*/
int flag=0;
if(!P){
printf("0 0\n");
return;
}
while(P){ /*此处为输出格式的设置,第一项前面没有空格,然后第一项之后每一项都间隔长空格*/
if(!flag)
flag=1;
else
printf(" ");
printf("%d %d",P->coef,P->expon);
P=P->link;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Polynomial P1,P2,PM,PA;
printf("请输入多项式P1的项数:");
P1=ReadPoly();
printf("请输入多项式P2的项数:");
P2=ReadPoly();
PM=Mult(P1,P2);
printf("多项式P1和P2的乘积为:");
PrintPoly(PM);
printf("\n");
PA=Add(P1,P2);
printf("多项式P1和P2的和为:");
PrintPoly(PA);
return 0;
}