#include <stdio.h>
#define NULL 0
typedef struct LNode{
int coef;
int expn;
struct LNode *next;} term;
typedef struct {
term *head,*tail;
int len;} LinkList;
void InitTerm(term *P)
{P->next=NULL;
}
void InitList(LinkList *L)
{L->head=L->tail=NULL;
L->len=0;
}
void CreatPolyn(term *P,LinkList *L,int m)
{term *S,*T;int i;
InitList(L);InitTerm(P);
T=L->head=P;
T->coef=0;T->expn=-1;
for(i=1;i<=m;++i) {S=(term *)malloc(sizeof(term)); InitTerm(S);
scanf("%d %d",&S->coef,&S->expn);
T->next=S;free(S); T=T->next; } (我想是不是这里出现的总是,但我就是找不出哪里有问题,觉得都是对的)
L->tail=T;L->len=m;
}
void AddPolyn(term *Pa,LinkList *La,term *Pb,LinkList *Lb)
{term *ha,*hb,*qa,*qb;int n;float sum;
ha=La->head;hb=Lb->head;
qa=Pa->next;qb=Pb->next;
while (qa && qb)
{if(qa->expn>qb->expn)n=1;
else if(qa->expn<qb->expn)n=-1;
else n=0;
switch(n) { case -1: ha=qa;qa=qa->next;break;
case 0: sum=qa->coef+qb->coef;
if(sum!=0.0){ qa->coef=sum;ha=qa;qa=qa->next;hb=qb;qb=qb->next;}
else {ha->next=qa=qa->next;hb->next=qb=qb->next;} break;
case 1: hb=qb;qb=qb->next; ha->next=hb;qb->next=qa;
hb=qb;qb=qb->next; break; }}
if(!Pb->next)La->tail=Pb->next; free(Pb);
}
void PrintPolyn(term *P)
{term *h;
h=P->next;
while(h!=NULL){ printf("Y="); printf("%dx(%d)+",h->coef,h->expn);
h=h->next;
}
printf("\b \n"); (输出时出现了死循环,是有循环结束标志的嘛,怎么会这样?)
}
void main()
{term *Pa,*Pb; LinkList *La,*Lb; int n;
Pa=(term *)malloc(sizeof(term));
Pb=(term *)malloc(sizeof(term));
La=(LinkList *)malloc(sizeof(LinkList));
Lb=(LinkList *)malloc(sizeof(LinkList));
puts("Now,Creat the first polynomail:");
puts("\nplease input the numbers of the first polynomail: ");
scanf("%d",&n);
puts("\nPlease input coef and expn each term with order from small to large by expn:\n");
CreatPolyn(Pa,La,n); puts("the first polynomail is:\n"); PrintPolyn(Pa);
puts("Now,Creat the second polynamail:\n");
puts("please input the numbers of the second polynamail:\n");
scanf("%d",&n);
puts("\nPlease input coef and expn each term with order from small to large yb expn:\n");
CreatPolyn(Pb,Lb,n); puts("the second polynomail is:\n"); PrintPolyn(Pb);
AddPolyn(Pa,La,Pb,Lb);
puts("the result is:\n");
PrintPolyn(Pa);
}