链表解决多项式相加问题

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

//链表解决多项式相加问题#includeiostreamusingnamespacestd;typedefstructPNode{floatcoef;intexpn;structPNode*next;}PNode,*Polynomial;//定义新类型voidCreatPolyn(Polynomial&p,intm)//创建链表{inti;Polynomials,pre,q;p=newPNode;p-next=NULL;for(i=1;i=m;i++){s=newPNode;cins-coefs-expn;pre=p;q=p-next;while(q&&q-expns-expn)//找到指数位置,按指数递增{pre=q;q=q-next;}s-next=q;pre-next=s;}}voidAddPolyn(Polynomial&pa,Polynomial&pb)//多项式相加{Polynomialp1,p2,p3,r,q;floatsum;p1=pa-next;p2=pb-next;p3=pa;p3-next=NULL;while(p1&&p2)//当p1,p2都没空时,进行循环{if(p1-expn==p2-expn)//当指数相同时,相加,结果放在头结点之后{sum=p1-coef+p2-coef;if(sum!=0){p1-coef=sum;q=p1-next;//p3=p1;p1-next=p3-next;p3-next=p1;p1=q;r=p2;p2=p2-next;deleter;}else{r=p1;p1=p1-next;deleter;r=p2;p2=p2-next;deleter;}}elseif(p1-expnp2-expn)//指数不同时,取指数小的先插到头结点之后{q=p1-next;p1-next=p3-next;p3-next=p1;p1=q;}else{q=p2-next;p2-next=p3-next;p3-next=p2;p2=q;}}if(p1==NULL)//当一方为空时,去另一方倒置插入头结点之后{while(p2){q=p2-next;p2-next=p3-next;p3-next=p2;p2=q;}}if(p2==NULL){while(p1){q=p1-next;p1-next=p3-next;p3-next=p1;p1=q;}}deletepb;}voidmain(){Polynomialpa,pb,p;intm;cout请输入第一个多项式的项数:endl;cinm;cout请输入第一个多项式:endl;CreatPolyn(pa,m);/*p=pa-next;while(p){if(p-coef0)cout+p-coef;elsecoutp-coef;cout(X)p-expn;p=p-next;}*/cout请输入第二个多项式的项数:endl;cinm;cout请输入第二个多项式:endl;CreatPolyn(pb,m);/*p=pb-next;while(p){if(p-coef0)cout+p-coef;elsecoutp-coef;cout(X)p-expn;p=p-next;}*/AddPolyn(pa,pb);p=pa-next;cout两个多项式相加和为:endl;if(!p)cout0endl;else{coutp-coef;cout(X)^p-expn;p=p-next;while(p){if(p-coef0)cout+p-coef;elsecoutp-coef;cout(X)^p-expn;p=p-next;}}}

1 / 3
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功