两个一元多项式相加

来源:互联网 发布:php页面自动跳转代码 编辑:程序博客网 时间:2024/04/30 07:06
程序运行结果如下:
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:18px;"># include<stdio.h></span>
# 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);elseprintf("%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,*s1,*s2,*s=NULL; float c; int e; s1=h1; 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; 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; } } 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;}}int main(){ListNode *head1,*head2,*head;printf("创建第一个多项式:\n"); head1=createpoly();printf("创建第二个多项式:\n");head2=createpoly();printf("将两个多项式相加:\n");head=addpoly(head1,head2);disppoly(head);deletepoly(head);}  </span>

0 0
原创粉丝点击