资源描述:
《多项式相加函数(数据结构_c语言版)》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、一、编写一个程序用单链表存储多项式,并实现两个多项式相加的函数。【源程序】#include#include#defineMAX20typedefstruct{floatcoef;intexp;}PolyArray[MAX];typedefstructpnode{floatcoef;//系数intexp;//指数structpnode*next;}PolyNode;voidDispPoly(PolyNode*L)//输出多项式{PolyNode*p=L->next;while(p!=NULL){printf("%gx^%d",p->
2、coef,p->exp);p=p->next;}printf("");}voidCreateListR(PolyNode*&L,PolyArraya,intn)//尾插法建立单链表{PolyNode*s,*r;inti;L=(PolyNode*)malloc(sizeof(PolyNode));//创建头结点L->next=NULL;r=L;//r始终指向终端结点,开始时指向头结点for(i=0;icoef=a[i].coef;s->exp=a[i].e
3、xp;r->next=s;//将*s插入*r之后r=s;}r->next=NULL;}voidSort(PolyNode*&head)//按exp域递减排序{PolyNode*p=head->next,*q,*r;if(p!=NULL){r=p->next;p->next=NULL;p=r;while(p!=NULL){r=p->next;q=head;while(q->next!=NULL&&q->next->exp>p->exp)q=q->next;p->next=q->next;q->next=p;p=r;}}}voidAdd(PolyNode*ha,PolyN
4、ode*hb,PolyNode*&hc)//求两个有序集合的并{PolyNode*pa=ha->next,*pb=hb->next,*s,*tc;floatc;hc=(PolyNode*)malloc(sizeof(PolyNode));tc=hc;while(pa!=NULL&&pb!=NULL){if(pa->exp>pb->exp){s=(PolyNode*)malloc(sizeof(PolyNode));//复制结点s->exp=pa->exp;s->coef=pa->coef;tc->next=s;tc=s;pa=pa->next;}elseif(pa->
5、expexp){s=(PolyNode*)malloc(sizeof(PolyNode));//复制结点s->exp=pb->exp;s->coef=pb->coef;tc->next=s;tc=s;pb=pb->next;}else{c=pa->coef+pb->coef;if(c!=0)//系数之和不为0事创建新结点{s=(PolyNode*)malloc(sizeof(PolyNode));s->exp=pa->exp;s->coef=c;tc->next=s;tc=s;}pa=pa->next;pb=pb->next;}}if(pb!=NULL)pa
6、=pb;//复制余下的结点while(pa!=NULL){s=(PolyNode*)malloc(sizeof(PolyNode));//复制结点s->exp=pa->exp;s->coef=pa->coef;tc->next=s;tc=s;pa=pa->next;}tc->next=NULL;}voidmain(){PolyNode*ha,*hb,*hc;PolyArraya={{1.5,0},{2.5,1},{3.3,3},{-2.5,5}};PolyArrayb={{-1.5,0},{2.5,1},{3.7,3},{-2.5,5},{5.6,7}};Create
7、ListR(ha,a,4);CreateListR(hb,b,5);printf("原多项式A为:");DispPoly(ha);printf("原多项式B为:");DispPoly(hb);Sort(ha);Sort(hb);printf("有序多项式A:");DispPoly(ha);printf("有序多项式B:");DispPoly(hb);Add(ha,ha,hc);printf("多项式相加结果:");DispPoly(hc);printf("");}