您好,欢迎访问三七文档
问题描述:有两个指数递减的一元多项式,写一程序先求这两个多项式的和,再求它们的积。提示1:用带表头结点的单链表作为多项式的存储表示;要建立两个单链表;多项式相加就是要把一个单链表中的结点插入到另一个单链表中去,要注意插入、删除操作中指针的正确修改。#includestdio.h#includestdlib.h#includemalloc.htypedefstructpoynomial{intcoef,ex;structpoynomial*next;}POY;POY*create_poy(void);POY*add_poy(POY*,POY*);POY*mul_poy(POY*,POY*);voidprint_poy(POY*);intmain(void){POY*heada=NULL,*headb=NULL,*headsum=NULL,*headmul=NULL;POY*headqa=NULL,*headqb=NULL;printf(createthefirstmultinomial:\n);heada=create_poy();printf(createthesecondmultinomial:\n);headb=create_poy();printf(Thefirstmultinomial:\n);print_poy(heada);printf(Thesecondmultinomial:\n);print_poy(headb);headsum=add_poy(heada,headb);printf(Thesummultinomial:);print_poy(headsum);headmul=mul_poy(heada,headb);printf(Themulmultinomial:);print_poy(headmul);return0;}//创建POY*create_poy(){intiA=0,iE=0;POY*head=NULL,*s=NULL,*r=NULL;head=(POY*)malloc(sizeof(POY));r=head;printf(pleaseinputcoefandexponent:\n);scanf(%d%d,&iA,&iE);while(iA!=0){s=(POY*)malloc(sizeof(POY));s-coef=iA,s-ex=iE;r-next=s;r=s;scanf(%d%d,&iA,&iE);}r-next=NULL;returnhead;}//相加POY*add_poy(POY*p1,POY*p2)//多项式相加{POY*head,*tmp,*s;intvalue;p1=p1-next;p2=p2-next;head=tmp=(POY*)malloc(sizeof(POY));head-next=NULL;while(p1&&p2){if(p1-ex==p2-ex){value=p1-coef+p2-coef;if(value!=0){s=(POY*)malloc(sizeof(POY));s-coef=value;s-ex=p1-ex;s-next=NULL;}p1=p1-next;p2=p2-next;}elseif(p1-exp2-ex){s=(POY*)malloc(sizeof(POY));s-coef=p1-coef;s-ex=p1-ex;s-next=NULL;p1=p1-next;}else{s=(POY*)malloc(sizeof(POY));s-coef=p2-coef;s-ex=p2-ex;s-next=NULL;p2=p2-next;}if(head-next==NULL){head-next=s;tmp=s;}else{tmp-next=s;tmp=s;}}tmp-next=p1?p1:p2;returnhead;}//相乘POY*mul_poy(POY*p1,POY*p2){POY*head;POY*t,*q,*s,*r;head=(POY*)malloc(sizeof(POY));head-next=NULL;r=(POY*)malloc(sizeof(POY));r-next=NULL;for(t=p1-next;t;t=t-next){for(q=p2-next;q;q=q-next){s=(POY*)malloc(sizeof(POY));r-next=s;s-coef=q-coef*t-coef;s-ex=q-ex+t-ex;s-next=NULL;head=add_poy(r,head);}}returnhead;}//输出voidprint_poy(POY*head){POY*p=NULL;p=head-next;if(p==NULL)printf(ThemultinomialisNULL.\n);else{do{if(p-coef=0)printf(+%dx^%d,p-coef,p-ex);elseprintf(%dx^%d,p-coef,p-ex);p=p-next;}while(p!=NULL);printf(\n);}}POY*qiudao(POY*p){POY*s;s=p;while(p){p-coef=(p-coef)*(p-ex);p-ex=(p-ex)-1;p=p-next;}returns;}
本文标题:多项式
链接地址:https://www.777doc.com/doc-1910221 .html