资源描述:
《一元稀疏多项式源代码.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include#includetypedefstructpolynomial{floatcoef;intexpn;structpolynomial*next;}*polyn,polynomial;voidinsertpolyn(polynp,polynh){//插入p;polynq1,q2;if(p->coef==0)free(p);else{q1=h;q2=q1->next;while(q2&&p->expn>q2->expn){q1=q1->next;q2=q2->next;}i
2、f(q2&&p->expn==q2->expn){q2->coef+=p->coef;free(p);if(q2->coef==0){q1->next=q2->next;free(q2);}}else{p->next=q2;q1->next=p;}}}voiddestroypolyn(polynp){//销毁链表polynq1,q2;q1=p->next;if(q1){q2=q1->next;while(q1->next){free(q1);q1=q2;q2=q2->next;}}free(q1);}voidprintpo
3、lyn(polynp){//打印多项式polynq=p->next;intflag=0;if(!q)putchar('0');while(q){if(q->coef!=0){if(q->expn==0){printf("%f",q->coef);//x^0flag++;}else{if(flag==0){if(q->expn==1){if(q->coef!=1&&q->coef!=-1)printf("%fX",q->coef);elseif(q->coef==1)printf("X");elseprintf("-X");
4、}else{if(q->coef!=1&&q->coef!=-1)printf("%fX^%d",q->coef,q->expn);elseif(q->coef==1)printf("X^%d",q->expn);elseprintf("-X^%d",q->expn);}flag++;}else{if(q->expn==1){if(q->coef>0&&q->coef!=1)printf("+%fX",q->coef);elseif(q->coef==1)printf("+X");elseif(q->coef==-1)pr
5、intf("-X");elseprintf("%fX",q->coef);}else{if(q->coef>0&&q->coef!=1)printf("+%fX^%d",q->coef,q->expn);elseif(q->coef==1)printf("+X^%d",q->expn);elseif(q->coef==-1)printf("-X^%d",q->expn);elseprintf("%fX^%d",q->coef,q->expn);}}}}q=q->next;}}polyncreatpolyn(polynhea
6、d,intm){//创建项数为m,头指针为head的单链表polynp;inti;head=(polyn)malloc(sizeof(structpolynomial));head->next=NULL;for(i=0;icoef,&p->expn);insertpolyn(p,head);}returnhead;}intcompare(polynpa,polynpb){//比较多项式指数i
7、f(pa&&pb){if(pa->expnexpn)return1;//pa=pa->next;elseif(pa->expn>pb->expn)return-1;//insertelsereturn0;//pa->expn==pb->expn}elseif(!pb)return1;//pb已读完,elsereturn-1;//pb未读完}polynaddpolyn(polynpa,polynpb){//实现多项式的相加polynqa=pa->next;polynqb=pb->next;polynq=pa;pol
8、ynp;while(qa
9、
10、qb)switch(compare(qa,qb)){case1:{q=q->next;qa=qa->next;break;}case-1:{p=(polyn)malloc(sizeof(structpolynomial));p->coef=qb->coef;p->expn=q