两个多项式求和问题 有错误求大神修改!
程序代码:
#include<stdio.h> #include<stdlib.h> struct node { int exp; float coef; struct node *next; }; typedef struct node ListNode; ListNode *createpoly() /*创建多项式列表*/ { ListNode *h=NULL,*p,*q=NULL; int e; float c; printf("请输入系数和指数:"); scanf("%f,%d",&c,&e); while(e!=0||c!=0) { p=(ListNode*)malloc(sizeof(ListNode)); p->coef=c; p->exp=e; p->next=NULL; if(h==NULL) h=p; else q->next=p; q=p; printf("请输入系数和指数:"); scanf("%f,%d",&c,&e); } return h; } void disppoly(ListNode *h) /*输出多项式*/ { ListNode *p; p=h; while(p!=NULL) { if(p->exp==0) printf("%.2f",p->coef); else printf("%fx^%d",p->coef,p->exp); p=p->next; if(p!=NULL) printf("+"); } printf("\n"); ListNode *addpoly(ListNode *h1,ListNode *h2) /*将两个多项式相加*/ { ListNode *p,*r=NULL,*si,*s2,*s=NULL; float c; s1=hi; s2=h2; while(s1!=NULL&&s2!=NULL) { if(s1->exp==s2->exp) { c=s1->coef+s2->coef; e=s1->exp; s1=s1->next; s2=s2->next; } else if(s1->exp==s2->exp) { c=s1->coef; e=s1->exp; s1=s1->next; } else { c=s2->coef; e=s2->exp; s1=s2->next; } if(c!=0) { p=(ListNode*)malloc(sizeof(ListNode)); p->coef=c; p->exp=e; p->next=NULL; if(s==NULL) s=p; else r->next=p; r=p; } } while(s1!=NULL) { c=s1->coef; e=s1->exp; s1=s1->next; if(c!=0) { p=(ListNode*)malloc(sizeof(ListNode)); p->coef=c; p->exp=e; p->next=NULL; if(s==NULL) s=p; else r->next=p; r=p; } while(s2!=NULL) { c=s2->coef; e=s2->exp; s2=s2->next; if(c!=0) { p=(ListNode*)malloc(sizeof(ListNode)); p->coef=c; p->exp=e; p->next=NULL; if(s==NULL) s=p; else r->next=p; r=p; } } return s; } void deletepoly(ListNode *h) /*释放多项式所占用内存单元*/ { ListNode *p,*r=h; while(r!=NULL) { p=r->next; free(r); r=p; } } void main() { ListNode *head1,*head2,head; printf("创建第一个多项式:\n"); head1=createpoly(); printf("创建第二个多项式:\n"); head2=createpoly(); head=addpoly(head1,head2); disppoly(head); deletepoly(head); }