这是题目信息:
02-线性结构2 一元多项式的乘法与加法运算 (20 point(s))
下面是我的代码:
#include<iostream>
using namespace std;
typedef struct PolyNode *PolyPtr;
struct PolyNode{
int coef;
int expo;
PolyPtr next;
};
PolyPtr readPoly();
PolyPtr Add(PolyPtr A, PolyPtr B);
PolyPtr Mult(PolyPtr A, PolyPtr B);
void Attach(int c,int e,PolyPtr *LPtr);
void PrintPoly(PolyPtr LPtr);
int main(int argc, char const *argv[])
{
PolyPtr A,B,A1,B1;
A = readPoly();
B = readPoly();
B1 = Mult(A,B);
PrintPoly(B1);
A1 = Add(A,B);
PrintPoly(A1);
return 0;
}
PolyPtr readPoly()
{
int N,c,e;
PolyPtr LPtr,head;
head = new PolyNode;
head->next = NULL;
LPtr = head;
scanf("%d",&N);
while(N--)
{
scanf("%d%d",&c,&e);
Attach(c,e,&LPtr);
}
return head;//返回头节点
}
void Attach(int c,int e, PolyPtr *LPtr)
{
PolyPtr temp;
temp = new PolyNode;
temp->next = NULL;
temp->coef = c;
temp->expo = e;
(*LPtr)->next = temp;
*LPtr = temp;
}
PolyPtr Add(PolyPtr A, PolyPtr B)
{
PolyPtr head,LPtr;
int sum;
head = new PolyNode;
head->next = NULL;
LPtr = head;
A = A->next;
B = B->next;
while(A&&B)
{
if(A->expo == B->expo)//如果两项的指数相同
{
sum = A->coef + B->coef;
if(sum)
Attach(sum, A->expo, &LPtr);
A = A->next;
B = B->next;
}
else if(A->expo > B->expo)
{
if(A->coef)
Attach(A->coef,A->expo,&LPtr);
A = A->next;
}
else{
if(B->coef)
Attach(B->coef,B->expo,&LPtr);
B = B->next;
}
}
for(;A;A = A->next)Attach(A->coef,A->expo,&LPtr);
for(;B;B = B->next)Attach(B->coef, B->expo,&LPtr);
return head;
}
PolyPtr Mult(PolyPtr A, PolyPtr B)
{
int c,e;
A = A->next;
B = B->next;
if(!A||!B)return NULL;
PolyPtr temp,B0,head,LPtr;
head = new PolyNode;
head->next = NULL;
LPtr = head;
B0 = B;
while(B)//先用A的第一项乘B,得到一个结果表达式
{
Attach(A->coef*B->coef, A->expo+B->expo, &LPtr);
B = B->next;
}
A = A->next;
while(A)
{
B = B0;
LPtr = head;
while(B)
{
c = A->coef * B->coef;
e = A->expo + B->expo;
while(LPtr->next && LPtr->next->expo > e)
LPtr = LPtr->next;
if(LPtr->next && LPtr->next->expo == e)
{
if(LPtr->next->coef + c)
LPtr->next->coef += c;
else{
temp = LPtr->next;
LPtr->next = temp->next;
delete temp;
}
}
else{
temp = new PolyNode;
temp->coef = c;
temp->expo = e;
temp->next = LPtr->next;
LPtr->next = temp;
LPtr = LPtr->next;
}
B = B->next;
}
A = A->next;
}
return head;
}
void PrintPoly(PolyPtr LPtr)
{
LPtr = LPtr->next;
int flag = 1;
if(!LPtr){
printf("0 0\n");
return;
}
while(LPtr)
{
if(flag == 1)flag = 0;
else{
printf(" ");
}
printf("%d %d",LPtr->coef,LPtr->expo);
LPtr = LPtr->next;
}
printf("\n");
}
不知道哪里有问题,一直不能通过第四个用例,请大神帮忙看一下,谢谢!