02-线性结构2 一元多项式的乘法与加法运算 （20 point(s)）

`````` #include<iostream>
using namespace std;
typedef struct PolyNode *PolyPtr;
struct PolyNode{
int coef;
int expo;
PolyPtr next;
};

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;
B1 = Mult(A,B);
PrintPoly(B1);
PrintPoly(A1);

return 0;
}

{
int N,c,e;
scanf("%d",&N);
while(N--)
{
scanf("%d%d",&c,&e);
Attach(c,e,&LPtr);
}
}

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;
}

{
int sum;
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);

}

PolyPtr Mult(PolyPtr A, PolyPtr B)
{
int c,e;
A = A->next;
B = B->next;
if(!A||!B)return NULL;

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;
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;
}
}

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");
}
``````

0
zhaijiayu666 回复Ⅰ折跃: 不知道...
4 个月之前 回复
Ⅰ折跃 请问您现在知道了吗
6 个月之前 回复