标签:
程序运行结果如下:
<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); 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,*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>
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qjt19950610/article/details/47312711