您的位置:首页 > 其它

多项式乘法与加法运算

2017-08-17 17:40 435 查看
#include "stdio.h"
#include "stdlib.h"

typedef struct PolyNode *Polynomial;
struct PolyNode {
int coef;
int expon;
Polynomial link;
};

void Attach(int c, int e, Polynomial *pRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
P->link = NULL;
(*pRear)->link = P;
(*pRear) = P;
}

Polynomial ReadPoly()
{
int n, c, e;
Polynomial t, P, Rear;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->link = NULL;
Rear = P;
scanf("%d", &n);
while (n>0) {
scanf("%d %d", &c, &e);
Attach(c, e, &Rear);    //传二级指针,使得P 和 Rear 能够与新结点连接
n--;
}
t = P;
P = P->link;
free(t);
return P;
}

Polynomial MultPoly(Polynomial P1,Polynomial P2)
{
Polynomial P,t,t1,t2,Rear;
int c,e;

if(!P1 || !P2)return NULL;

t1 = P1,t2 = P2;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->link = NULL;
Rear = P;
while(t2){
Attach(t1->coef*t2->coef,t1->expon+t2->expon,
ba6b
&Rear);
t2=t2->link;
}
t1 = t1->link;
while(t1){
t2 = P2;Rear = P;
while(t2){
c = t1->coef * t2->coef;
e = t1->expon+t2->expon;
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);
t2 = NULL;
return P;
}

Polynomial AddPoly(Polynomial P1,Polynomial P2)
{
Polynomial P,temp,t1,t2,Rear;
t1=P1,t2=P2;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->link = NULL;
Rear = P;
while(t1 && t2){
if(t1->expon > t2->expon){
Attach(t1->coef,t1->expon,&Rear);
t1=t1->link;
}else if(t1->expon == t2->expon){
int t=t1->coef+t2->coef;
if(t){
Attach(t,t1->expon,&Rear);
}
t1=t1->link;
t2=t2->link;
}else{
Attach(t2->coef,t2->expon,&Rear);
t2=t2->link;
}
}
while(t1){
Attach(t1->coef,t1->expon,&Rear);
t1 = t1->link;
}
while(t2){
Attach(t2->coef,t2->expon,&Rear);
t2=t2->link;
}
Rear->link = NULL;
temp = P;
P = P->link;
free(temp);
temp = NULL;
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 main()
{
Polynomial P1, P2, PP, PS;
printf("scanf P1:\n");
P1 = ReadPoly();
printf("Your P1 is : ");
PrintPoly(P1);
printf("\nscanf P2:\n");
P2=ReadPoly();
printf("Your P2 is : ");
PrintPoly(P2);
PP=MultPoly(P1,P2);
printf("\nMultPoly(P1,P2)\n");
PrintPoly(PP);
PS=AddPoly(P1,P2);
printf("\nAddPoly(P1,P2)\n");
PrintPoly(PS);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: