#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <conio.h>
typedef struct node { float coef; int expn; struct node * next; } PolyNode;
PolyNode * Create_Poly(char ch) //输入多项式 { PolyNode * p, *s,*r; float x; int y; p=(PolyNode *)malloc(sizeof(PolyNode)); p->next=NULL; printf("请输入一元多项式%c:(格式:系数 指数,指数递增,以0 0结束.)\n",ch); scanf("%f %d",&x,&y); while(x!=0) { s=(PolyNode *)malloc(sizeof(PolyNode)); s->coef=x; s->expn=y; s->next=NULL; if(p->next==NULL) { p->next=s; r=s; } else { r->next=s; r=s; } scanf("%f %d",&x,&y); } return p; }
PolyNode * Add_Poly(PolyNode * f,PolyNode * g) //多项式相加 { PolyNode * fg; PolyNode *t,*q,*s,*r; float m; t=f->next; q=g->next; fg=r=(PolyNode*)malloc(sizeof(PolyNode)); fg->next=NULL; while(t&&q) { if(t->expn==q->expn) //指数相等时系数相加 { m=t->coef+q->coef; if(m!=0) //系数为不0时加到结果中去 { s=(PolyNode *)malloc(sizeof(PolyNode)); s->coef=m; s->expn=t->expn; s->next=NULL; } t=t->next; q=q->next; } else //指数小的加到结果中去再后移 if(t->expn<q->expn) { s=(PolyNode *)malloc(sizeof(PolyNode)); s->coef=t->coef; s->expn=t->expn; s->next=NULL; t=t->next; } else { s=(PolyNode *)malloc(sizeof(PolyNode)); s->coef=q->coef; s->expn=q->expn; s->next=NULL; q=q->next; }
if(fg->next==NULL) { fg->next=s; r=s; } else { r->next=s; r=s; } }//while r->next=t?t:q; //把没加完的接上 return fg; }
void Out_Poly(PolyNode * f) //输入多项式 { PolyNode *t; t=f->next; if(!f->next){ printf("0\n"); return; } while(t) { if(t->coef>0&&f->next!=t) printf("+"); if(t->expn==0) printf("%f",t->coef); else printf("%f*X^%d",t->coef,t->expn); t=t->next; } printf("\n"); }