这道习题有点难。。。自己实现了一遍,还是有小的问题存在。无法达到题目要求的格式。但是已经可以计算出正确结果了。如果有发现问题的话请大家多多指正。谢谢!!!
#include <stdio.h>
#include <stdlib.h>
typedef struct SNode* Polynomial;
struct SNode {
int coef;
int exp;
struct SNode* next;
};
int Compare(int a, int b);
void Attach(int coef, int exp, Polynomial *prear);
Polynomial ReadPoly();
void PrintPoly(Polynomial P);
Polynomial AddPoly(Polynomial P1, Polynomial P2);
Polynomial MultPoly(Polynomial P1, Polynomial P2);
int Compare(int a, int b)
{
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
void Attach(int coef, int exp, Polynomial *prear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct SNode));
P->coef = coef;
P->exp = exp;
P->next = NULL;
/*将P插入到当前结果表达式尾项的最后面*/
(*prear)->next = P;
(*prear) = P;
}
Polynomial ReadPoly()
{
Polynomial P, rear, temp;
int N;
P = (Polynomial)malloc(sizeof(struct SNode));
rear = P;
P->next = NULL;
int coef, exp;
scanf("%d", &N);
while (N--)
{
scanf("%d %d", &coef, &exp);
Attach(coef, exp, &rear);
}
temp = P;
P = P->next;
free(temp);
return P;
}
void PrintPoly(Polynomial P)
{
int flag = 0;
if (!P)
printf("0 0\n");
while (P)
{
if (!flag)
flag = 1;
else
printf(" ");
if (P->coef != 0)
{
printf("%d %d", P->coef, P->exp);
P = P->next;
}
else
P = P->next;
}
printf("\n");
}
Polynomial AddPoly(Polynomial P1, Polynomial P2)
{
Polynomial P, rear, temp;
P = (Polynomial)malloc(sizeof(struct SNode));
P->next = NULL;
rear = P;
while (P1&&P2)
{
switch (Compare(P1->exp, P2->exp))
{
case 1:
Attach(P1->coef, P1->exp, &rear);
P1 = P1->next;
break;
case -1:
Attach(P2->coef, P2->exp, &rear);
P2 = P2->next;
break;
case 0:
if(P1->coef + P2->coef)
Attach(P1->coef + P2->coef, P2->exp, &rear);
P1 = P1->next;
P2 = P2->next;
break;
}
}
for (; P1; P1=P1->next)
Attach(P1->coef, P1->exp, &rear);
for (; P2;P2= P2->next)
Attach(P2->coef, P2->exp, &rear);
rear->next = NULL;
temp = P;
P = P->next;
free(temp);
return P;
}
Polynomial MultPoly(Polynomial P1, Polynomial P2)
{
Polynomial P, rear, temp,temp1,temp2;
Polynomial MultP;
MultP = (Polynomial)malloc(sizeof(struct SNode));
MultP->coef = 0;
MultP->exp = 0;
MultP->next = NULL;
P = (Polynomial)malloc(sizeof(struct SNode));
rear = P;
temp2 = P;
P->next = NULL;
temp1 = P2;
for (; P1; P1 = P1->next)
{
while (temp1) {
Attach(P1->coef*temp1->coef, P1->exp + temp1->exp, &rear);
temp1 = temp1->next;
}
rear->next = NULL;
temp = temp2;
temp2 = temp2->next;
MultP = AddPoly(MultP, temp2);
temp1 = P2;
rear = P;
temp2 = P;
}
return MultP;
}
int main(void)
{
Polynomial P1, P2, P,P0;
P1 = ReadPoly();
P2 = ReadPoly();
P0 = MultPoly(P1, P2);
PrintPoly(P0);
P = AddPoly(P1, P2);
PrintPoly(P);
}
最后的多项式乘法函数写的风格不够简明,不懂的可以问我。但个人感觉好像比我看到的好多代码都简单些。希望大家批评指正。