题100.2021秋周练习-2-1 Add Two Polynomials (20 分)
一、题目
二、题解
本题要注意的是1.该链表带假的头节点2.当结果多项式的单项式系数为0时,该单项式不能接入结果链表中,这貌似可以从0多项式(所以单项式系数为0)为空链表可以推出(反正我是没推出来,只单纯考虑了0多项式,导致测试点1过不去)
Polynomial Add( Polynomial a, Polynomial b )
{
Polynomial res;
res=(Polynomial)malloc(sizeof(struct Node));
PtrToNode head=res,head1=a,head2=b;
while(head1->Next&&head2->Next)
{
PtrToNode node=(PtrToNode)malloc(sizeof(struct Node));
node->Exponent=0;
node->Coefficient=0;
node->Next=NULL;
if(head1->Next->Exponent==head2->Next->Exponent)
{
node->Exponent=head1->Next->Exponent;
node->Coefficient=head1->Next->Coefficient+head2->Next->Coefficient;
head1=head1->Next;
head2=head2->Next;
if(node->Coefficient!=0)
{
head->Next=node;
head=node;
}
}
else if(head1->Next->Exponent>head2->Next->Exponent)
{
node->Exponent=head1->Next->Exponent;
node->Coefficient=head1->Next->Coefficient;
head->Next=node;
head=node;
head1=head1->Next;
}
else
{
node->Exponent=head2->Next->Exponent;
node->Coefficient=head2->Next->Coefficient;
head->Next=node;
head=node;
head2=head2->Next;
}
}
if(head1->Next)//当链表有剩余没接上时直接整条接上就好了
{
head->Next=head1->Next;
}
if(head2->Next)
{
head->Next=head2->Next;
}
return res;
}