3.6 编写将两个多项式相加的函数。不要毁坏输入数据。用一个链表实现。
我的想法是 先将两个多项式按照exponent(次方)进行排序,相同次方的进行合并,再将这两个多项式进行相加。
多项式的结构体定义如下:
struct Node
{
int coefficient;
int exponent;
Position next;
};
具体函数实现方法如下:
首先是排序算法:
/* 冒泡排序多项式,按照项的次数从小到大排序 */
void MPSort( Position h , int size )
{
Position p;
for( int i = 0; i < size-1; i++ )
{
p = h->next;
while( p != NULL && p->next != NULL )
{
if ( p->exponent > p->next->exponent )
{
Swap2Position( h, p, p->next ); //交换两个结点
}
else if ( p->exponent == p->next->exponent )
{
Union2Position( p, p->next ); //合并两个结点
}
else
{
p = p->next; //指针移到下一个结点
}
}
}
return;
}
/* 交换两个相邻的结点 */
void Swap2Position( Position h, Position p1, Position p2 )
{
Position p0;
p0 = FindPrevious( h, p1 );
p1->next = p2->next;
p2->next = p1;
p0->next = p2;
return;
}
/* 合并两个次数相同的结点 */
void Union2Position( Position p1, Position p2 )
{
if ( p1->exponent == p2->exponent )
{
p1->coefficient = p1->coefficient + p2->coefficient;
p1->next = p2->next;
free( p2 );
}
}
接着是多项式相加的算法 (按照次数升序排序的)
/* 将两个以排好序(升序)的多项式相加 */
Position Add2Polynomial( Position h1, Position h2 )
{
int size;
Position h;
Position p1, p2;
p1 = h1->next;
p2 = h2->next;
h = ( Position )malloc(sizeof(struct Node));
h->next = NULL;
while ( p1 != NULL && p2 != NULL )
{
if ( p1->exponent < p2->exponent )
{
InsertPolynomial( h, p1->coefficient, p1->exponent ); //将p1指向的结点插入到新的多项式中
p1 = p1->next;
size++;
}
else if ( p1->exponent > p2->exponent )
{
InsertPolynomial( h, p2->coefficient, p2->exponent ); //将p2指向的结点插入到新的多项式中
p2 = p2->next;
size++;
}
else
{
InsertPolynomial( h, p1->coefficient + p2->coefficient, p1->exponent ); //将两个结点的系数相加 然后插入到新的多项式中
p1 = p1->next;
p2 = p2->next;
size++;
}
}
while ( p1 != NULL )
{
InsertPolynomial( h, p1->coefficient, p1->exponent );
p1 = p1->next;
size++;
}
while ( p2 != NULL )
{
InsertPolynomial( h, p2->coefficient, p2->exponent );
p2 = p2->next;
size++;
}
//排序
MPSort( h, size );
return h;
}
void InsertPolynomial( Position h, int coefficient, int exponent )
{
Position tmpCell;
tmpCell = ( Position )malloc(sizeof(struct Node));
tmpCell->coefficient = coefficient;
tmpCell->exponent = exponent;
tmpCell->next = h->next;
h->next = tmpCell;
}