# 数据结构 一元多项式相加

/***************************/
/*一元多项式相加*/

#include<stdio.h>
#include<stdlib.h>
/
struct node
{
int coef; //系数
int expn;   //指数
struct node *next;
};
typedef struct node polynomial;

/**************建立带有表头的链表**************/
// poly用于保存系数和指数

polynomial *CreatePoly(int poly[], int len)
{
polynomial *ptr;
polynomial *newpoly;
int i;
for(i=0; i<len; i+=2)
{
newpoly = (polynomial *)malloc(sizeof(polynomial));
newpoly->coef = poly[i];
newpoly->expn = poly[i+1];
newpoly->next = NULL;
ptr->next = newpoly;
ptr = newpoly;
}
}

/*********销毁链表**************/
{
polynomial *ptr;
{
ptr = ptr->next;
}
}
/************输入链表****************/
{
polynomial *ptr;
while(ptr != NULL)
{
printf("(%d,%d)",ptr->coef, ptr->expn);
ptr = ptr->next;
}
printf("/n");
}

/***********链表相加/*****************/
//参数为两个要相加多项式的链表
//两个链表为从系数大到小排列
{
polynomial *ptr1, *ptr2, *ptr;
polynomial *newpoly;

while(ptr1 != NULL && ptr2 != NULL)  //都不为空时
{
newpoly = (polynomial *)malloc(sizeof(polynomial));
newpoly->next = NULL;
if(ptr1->expn > ptr2->expn)   //指数大的放到前面
{
newpoly->coef = ptr1->coef;
newpoly->expn = ptr1->expn;
ptr1 = ptr1->next;
}
else if(ptr1->expn < ptr2->expn)
{
newpoly->coef = ptr2->coef;
newpoly->expn = ptr2->expn;
ptr2 = ptr2->next;
}
else     //两指数相等，则系数＝两系数相加
{
newpoly->coef = ptr1->coef + ptr2->coef;
newpoly->expn = ptr1->expn;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
ptr->next = newpoly;
ptr = newpoly;
}
if(NULL == ptr1)    //ptr2 != null, ptr1 =＝ null时
{
while(ptr2 != NULL)    //直接复制ptr2到新链表中
{
newpoly = (polynomial *)malloc(sizeof(polynomial));
newpoly->next = NULL;
newpoly->coef = ptr2->coef;
newpoly->expn = ptr2->expn;
ptr->next = newpoly;
ptr = newpoly;
ptr2 = ptr2->next;
}
}
else if(NULL == ptr2)
{
while(ptr1 != NULL)
{
newpoly = (polynomial *)malloc(sizeof(polynomial));
newpoly->next = NULL;
newpoly->coef = ptr1->coef;
newpoly->expn = ptr1->expn;
ptr->next = newpoly;
ptr = newpoly;
ptr1 = ptr1->next;
}
}