参考陈越的数据结构,把其提供的程序重新写了一下,并重新组装。
名称:多项式的相乘和相加
代码如下:
#include <stdio.h> #include <stdlib.h> /* Name: Add and Mult of Polrnomial Copyright: Author: demosses Date: 06/04/17 10:32 Description: 数据结构链表编程题 */ typedef struct PolyNode *Polynomial; struct PolyNode{ int coef; int expon; Polynomial link; }; Polynomial ReadPoly(); void Attach(int c,int e,Polynomial *pRear); Polynomial Add(Polynomial P1,Polynomial P2); void PrintPoly(Polynomial P); Polynomial Mult(Polynomial P1,Polynomial P2); int main() { Polynomial P1,P2,PP,PS; P1=ReadPoly(); P2=ReadPoly(); PP=Mult(P1,P2); PS=Add(P1,P2); PrintPoly(PP); PrintPoly(PS); } Polynomial ReadPoly() { Polynomial P,Rear,t; int c,e,N; scanf("%d",&N); P=(Polynomial)malloc(sizeof(struct PolyNode)); P->link=NULL; Rear=P; while(N--){ scanf("%d %d",&c,&e); Attach(c,e,&Rear); } t=P;P=P->link;free(t); /*删除临时生成的头节点*/ return P; } 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; /*改变尾指针的数值*/ } Polynomial Add(Polynomial P1,Polynomial P2) { /*多项式相加*/ Polynomial t1,t2,P,Rear; t1=P1;t2=P2; P=(Polynomial)malloc(sizeof(struct PolyNode)); Rear=P;/*空头节点*/ while(t1&&t2){ if(t1->expon==t2->expon){ if(t1->coef+t2->coef) Attach(t1->coef+t2->coef,t1->expon,&Rear); t1=t1->link; t2=t2->link; } else if(t1->expon>t2->expon){ Attach(t1->coef,t1->expon,&Rear); t1=t1->link; } else { Attach(t2->coef,t2->expon,&Rear); t2=t2->link; } } while(t1){ Attach(t1->coef,t1->expon,&Rear); t1=t1->link; } while(t2){ Attach(t2->coef,t2->expon,&Rear); t2=t2->link; } t2=P;P=P->link;free(t2);/*删除空的头节点*/ return P; } Polynomial Mult(Polynomial P1,Polynomial P2) { /*多项式相乘*/ Polynomial P,Rear,t1,t2,t; int c,e; if(!P1||!P2) return NULL; t1=P1; t2=P2; P=(Polynomial)malloc(sizeof(struct PolyNode)); P->link=NULL; Rear=P; while(t2){ Attach(t1->coef*t2->coef,t1->expon+t2->expon,&Rear); t2=t2->link; } t1=t1->link; while(t1){ t2=P2;Rear=P; while(t2){ e=t1->expon+t2->expon; c=t1->coef*t2->coef; while(Rear->link&&Rear->link->expon>e) Rear=Rear->link; if(Rear->link&&Rear->link->expon==e) { if(Rear->link->coef+c) Rear->link->coef+=c; else { t=Rear->link; Rear->link=t->link; free(t); } } else{ t=(Polynomial)malloc(sizeof(struct PolyNode)); t->coef=c; t->expon=e; t->link=Rear->link; Rear->link=t; Rear=Rear->link; } t2=t2->link; } t1=t1->link; } t2=P; P=P->link; free(t2); return P; } void PrintPoly(Polynomial P) { int flag=1; Polynomial p1=P; if(!P){ printf("0 0 "); return; }//马上返回去 while(p1){ if (flag)/*让第一个数输入的不为空格*/ flag=0; else printf(" "); printf("%d %d",p1->coef,p1->expon); p1=p1->link; } printf(" "); }