#include<stdlib.h> typedef int datatype;
typedef struct node {float coef; /*多项式系数*/ int expn; /*多项式指数*/ struct node *next; }listnode;
typedef listnode *linklist;
/*---------创建带头结点的多项式链表--------*/ linklist creat() { linklist head,s,p,pre,r; float coef; int expn; head=(linklist)malloc(sizeof(listnode)); /*表头结点*/ head->next=NULL; scanf("%f",&coef); scanf("%d",&expn); while (coef!=0) /*用0作为结束标记*/ {s=(linklist)malloc(sizeof(listnode)); /*生成新结点*/ s->coef=coef; s->expn=expn; s->next=NULL; pre=head; /*插入到有序的多项式链表中去*/ p=head->next; while (p && p->expn <expn) { pre=p; p=p->next; } s->next=p; pre->next=s; scanf("%f",&coef); /*读下一项*/ scanf("%d",&expn); } return head; }
void print(linklist head) /*输出多项式链表*/ { linklist p; p=head->next; while (p) { printf("%f",p->coef); printf("%4d ",p->expn); p=p->next; } }
/*-------------多项式相加----------------*/ linklist add(linklist a,linklist b) { linklist p,q,head;
p=head=b; b=b->next; q=a->next; a->next=NULL; free(a); a=q; while(a&&p) { if(b->expn<a->expn) { p=b; b=b->next; } else if(b->expn==a->expn) { if((b->coef+a->coef)!=0) { b->coef=b->coef+a->coef; q=a->next; a->next=NULL; free(a); a=q; p=b; b=b->next; } else{ q=a->next; free(a); a=q; p->next=b->next; free(b); b=p->next; }
} else { q=a->next; p->next=a; a->next=b; p=a; a=q; } }
if(!(b->next)) b->next=a; return head; }
/*----主程序------*/ main() { linklist a,b,c; a=creat(); /*创建多项式链表a*/ print(a); printf("\n"); b=creat(); /*创建多项式链表b*/ print(b); printf("\n"); c=add(a,b); /* 计算多项式a+b */ print(c); }
[此贴子已经被作者于2004-11-07 12:07:21编辑过]