6-3-Add Two Polynomials-函数题
解题代码
Polynomial Add(Polynomial a, Polynomial b) {
Polynomial add = (Polynomial)malloc(sizeof(struct Node));
Polynomial ret = add;
add->Next = NULL;
Polynomial aa = a->Next, bb = b->Next;
while (aa&&bb) {
if (aa->Exponent > bb->Exponent) {
Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
temp->Exponent = aa->Exponent;
temp->Coefficient = aa->Coefficient;
temp->Next = NULL;
add->Next = temp;
add = temp;
aa = aa->Next;
}
else if (bb->Exponent > aa->Exponent) {
Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
temp->Exponent = bb->Exponent;
temp->Coefficient = bb->Coefficient;
temp->Next = NULL;
add->Next = temp;
add = temp;
bb = bb->Next;
}
else {
if (bb->Coefficient + aa->Coefficient) {
Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
temp->Exponent = aa->Exponent;
temp->Coefficient = bb->Coefficient + aa->Coefficient;
temp->Next = NULL;
add->Next = temp;
add = temp;
aa = aa->Next;
bb = bb->Next;
}
else {
aa = aa->Next;
bb = bb->Next;
}
}
}
while (aa) {
Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
temp->Exponent = aa->Exponent;
temp->Coefficient = aa->Coefficient;
temp->Next = NULL;
add->Next = temp;
add = temp;
aa = aa->Next;
}
while (bb) {
Polynomial temp = (Polynomial)malloc(sizeof(struct Node));
temp->Exponent = bb->Exponent;
temp->Coefficient = bb->Coefficient;
temp->Next = NULL;
add->Next = temp;
add = temp;
bb = bb->Next;
}
return ret;
}
测试结果
问题整理
1.注意指数相同、系数相加为零的情况。