《一元稀疏多项式源代码(4页).pdf》由会员分享,可在线阅读,更多相关《一元稀疏多项式源代码(4页).pdf(10页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、 一元稀疏多项式源代码页G o o d i s g o o d,b u t b e t t e r c a r r i e s i t.精 益 求 精,善 益 求 善。-2减相项实加多 完未,读已 数式较表链指为建式表毁销;入-#include#include typedef struct polynomial float coef;int expn;struct polynomial*next;*polyn,polynomial;void insertpolyn(polyn p,polyn h)/插入 p;polyn q1,q2;if(p-coef=0)free(p);else q1=h;q
2、2=q1-next;while(q2&p-expnq2-expn)q1=q1-next;q2=q2-next;if(q2&p-expn=q2-expn)q2-coef+=p-coef;free(p);if(q2-coef=0)-3减相项实加多 完未,读已 数式较表链指为建式表毁销;入-q1-next=q2-next;free(q2);else p-next=q2;q1-next=p;void destroypolyn(polyn p)/销毁链表 polyn q1,q2;q1=p-next;if(q1)q2=q1-next;while(q1-next)free(q1);q1=q2;q2=q2-n
3、ext;free(q1);-4减相项实加多 完未,读已 数式较表链指为建式表毁销;入-void printpolyn(polyn p)/打印多项式 polyn q=p-next;int flag=0;if(!q)putchar(0);while(q)if(q-coef!=0)if(q-expn=0)printf(%f,q-coef);/x0 flag+;else if(flag=0)if(q-expn=1)if(q-coef!=1&q-coef!=-1)printf(%fX,q-coef);else if(q-coef=1)printf(X);else printf(-X);else if(q
4、-coef!=1&q-coef!=-1)printf(%fX%d,q-coef,q-expn);else if(q-coef=1)printf(X%d,q-expn);-5减相项实加多 完未,读已 数式较表链指为建式表毁销;入-else printf(-X%d,q-expn);flag+;else if(q-expn=1)if(q-coef0&q-coef!=1)printf(+%fX,q-coef);else if(q-coef=1)printf(+X);else if(q-coef=-1)printf(-X);else printf(%fX,q-coef);else if(q-coef0&
5、q-coef!=1)printf(+%fX%d,q-coef,q-expn);else if(q-coef=1)printf(+X%d,q-expn);else if(q-coef=-1)printf(-X%d,q-expn);else printf(%fX%d,q-coef,q-expn);q=q-next;-6减相项实加多 完未,读已 数式较表链指为建式表毁销;入-polyn creatpolyn(polyn head,int m)/创建项数为 m,头指针为 head 的单链表 polyn p;int i;head=(polyn)malloc(sizeof(struct polynomia
6、l);head-next=NULL;for(i=0;icoef,&p-expn);insertpolyn(p,head);return head;int compare(polyn pa,polyn pb)/比较多项式指数 if(pa&pb)if(pa-expnexpn)return 1;/pa=pa-next;else if(pa-expnpb-expn)return-1;/insert else return 0;/pa-expn=pb-expn else if(!pb)return 1;/pb 已读完,-7减相项实加多 完未,读已 数式较表链指为建式表毁销;入-else return-1
7、;/pb 未读完 polyn addpolyn(polyn pa,polyn pb)/实现多项式的相加 polyn qa=pa-next;polyn qb=pb-next;polyn q=pa;polyn p;while(qa|qb)switch(compare(qa,qb)case 1:q=q-next;qa=qa-next;break;case-1:p=(polyn)malloc(sizeof(struct polynomial);p-coef=qb-coef;p-expn=qb-expn;p-next=qa;q-next=p;q=p;qb=qb-next;break;case 0:qa-
8、coef=qa-coef+qb-coef;-8减相项实加多 完未,读已 数式较表链指为建式表毁销;入-if(qa-coef!=0)qa=qa-next;q=q-next;qb=qb-next;else q-next=qa-next;free(qa);qa=q-next;qb=qb-next;break;return pa;polyn subtract(polyn pa,polyn pb)/实现多项式的相减 polyn qb=pb-next;while(qb!=NULL)qb-coef*=-1;qb=qb-next;-9减相项实加多 完未,读已 数式较表链指为建式表毁销;入-addpolyn(p
9、a,pb);return pa;int main()int group,i,m1,m2,flag;polyn pa=0;polyn pb=0;scanf(%d,&group);for(i=0;igroup;i+)scanf(%d%d%d,&m1,&m2,&flag);pa=creatpolyn(pa,m1);pb=creatpolyn(pb,m2);if(flag=0)pa=addpolyn(pa,pb);else pa=subtract(pa,pb);destroypolyn(pb);printpolyn(pa);destroypolyn(pa);printf(n);system(PAUSE);-10减相项实加多 完未,读已 数式较表链指为建式表毁销;入-return 0;