两个一元多项式相加的程序
#include
#include
#define MAX 5
//定义结点
struct LinkList{
int coefficient;
int power;
LinkList *next;
};
//创建链表
void CreateList(LinkList *&L,int a[],int b[], int n) {
LinkList *s;
int i;
L=(LinkList *)malloc(sizeof(LinkList));
L->next=NULL;
for(i=0;i { s=(LinkList *)malloc(sizeof(LinkList)); s->coefficient=a[i]; s->power=b[i]; s->next=L->next; L->next=s; } } //递增排序 void sort(LinkList *&L) { LinkList *p=L->next,*q,*r; if(p!=NULL) { r=p->next; p->next=NULL; p=r; while(p!=NULL) { r=p->next; q=L; while(q->next!=NULL&&q->next->power q=q->next; p->next=q->next; q->next=p; p=r; } } } //两个多项式相加 void ListAdd(LinkList *&L1,LinkList *&L2,LinkList *&L3) { int coefficient[2*MAX],power[2*MAX],i=0; LinkList *p=L1->next,*q=L2->next; while(p!=NULL&&q!=NULL) { if(p->power { coefficient[i]=p->coefficient; power[i]=p->power; i++; p=p->next; } else if(p->power>q->power) { coefficient[i]=q->coefficient; power[i]=q->power; i++; q=q->next; } else { coefficient[i]=p->coefficient+q->coefficient; power[i]=p->power; i++; p=p->next; q=q->next; } } while(p!=NULL) { coefficient[i]=p->coefficient; power[i]=p->power; i++; p=p->next; } while(q!=NULL) { coefficient[i]=q->coefficient; power[i]=q->power; i++; q=q->next; } CreateList(L3,coefficient,power,i); sort(L3); } //显示多项式 void DisplayList(LinkList *&L) { LinkList *p=L->next; if(p->power!=0) printf("%dx^%d",p->coefficient,p->power); else printf("%d",p->coefficient); p=p->next; while(p!=NULL) { if(p->power!=0) { if(p->coefficient>0) printf("+%dx^%d",p->coefficient,p->power); else printf("%dx^%d",p->coefficient,p->power); } else { if(p->coefficient>0) printf("+%d",p->coefficient); else printf("%d",p->coefficient); } p=p->next; } } //主函数 void main() { int coefficient[MAX],power[MAX],i=0; LinkList *L1,*L2,*LSum; printf("Input the coefficient of polynomial L1:\n"); //输入第一个多项式的系数 for(i=0;i scanf("%d",&coefficient[i]); printf("Input the power of polynomial L1:\n"); //输入第一个多项式的幂for(i=0;i scanf("%d",&power[i]); CreateList(L1,coefficient,power,MAX); printf("\nInput the coefficient of polynomial L2:\n"); //输入第二个多项式的系数 for(i=0;i scanf("%d",&coefficient[i]); printf("Input the power of polynomial L2:\n"); //输入第二个多项式的幂for(i=0;i scanf("%d",&power[i]); CreateList(L2,coefficient,power,MAX); printf("\n\npolynomial L1 as follow:\n"); //显示第一个多项式 sort(L1); DisplayList(L1); printf("\n\npolynomial L1 as follow:\n"); //显示第二个多项式 sort(L2); DisplayList(L2); printf("\n\n\nthe polynomial L1+L2:\n"); //求两个多项式的和并显示ListAdd(L1,L2,LSum); DisplayList(LSum); while(1); }