数据结构—一元多项式加法运算
采用不带头结点的单向链表,按照指数递减的顺序排列各项。
-
定义结点:
struct PolyNode{ int coef;//系数 int expon;//指数 struct PolyNode *link;//指向下一个结点的指针 }; typedef struct PolyNode *Ploynomial; Polynomial P1,P2;
-
算法思路:
![wangxining_2021-05-21_13-52-26](https://i-blog.csdnimg.cn/blog_migrate/3ad140977674f0fce4e6518a130bb563.png)
-
代码:
Polynomial PolyAdd (Polynomial P1 ,Polynomial P2) { Polynomial front ,rear ,temp; int sum; rear = (Polynomial)malloc(sizeof(struct PolyNode)); front = rear; while(P1 && P2)//当两个多像是均由非零项待处理 switch (Compare(P1->expon,P2->expon)){ case 1: Attach(P1->coef,P1->expon,&rear); P1 = P1->link; break; case -1: Attach(P2->coef,P2->expon,&rear); P2 = P2->link; break; case 0: sum = P1->coef+P2->coef; if(sum)Attach(sum,P1->expon,&rear); P1 = P1->link; P2 = P2->link; break; } //将未处理完的另一个多项式的所有节点依次复制到结果多项式中去 for(;P1;P1=P1->link)Attach(P1->coef,P1->expon,&rear); for(;P2;P2=P2->link)Attach(P2->coef,P2->expon,&rear); rear->link=NULL; temp = front; front = front->link;//令front指向结果多项式第一个非零项 free(temp);//释放临时空表头结点 return front; }
-
Attach函数
void Attach(int c,int e,Polynomial *pRear) { Polynomial P; P = (Polynomial)malloc(sizeof(struct PolyNode)); P->coef = c;//对新节点赋值 P->expon = e; p->link = NULL; (*pRear)->link = P; *pRear = P;//修改pRear值。 }