这个是求两个多项式之和,第一个多项式的数据输入之和按回车程序就运行出错了,求大神解答!
#include<stdio.h>
#include<stdlib.h>
struct node{int coef;
int exp;
struct node*link;
};
typedef struct node NODE;
NODE *ah,*bh,*ch;
NODE*creat(void)
{
char coef,exp;
int n=0;
NODE*head,*p,*q;
do
{
scanf("%c%c",&coef,&exp);
if(coef==0);
break;
n++;
p=(NODE*)malloc(sizeof(NODE));
p->coef=coef,p->exp=exp,p->link=NULL;
if(n==1)
head=p=q;
else
{
q->link=p;
q=p;
}
}while(1);
return head;
}
NODE*insert(NODE*pc,int c,int e)
{
NODE *t;
t=(NODE*)malloc(sizeof(NODE));
t->coef=c;
t->exp=e;
pc->link=t;
return t;
}
NODE *polyadd_l(ah,bh)
NODE *ah,*bh;
{
NODE*pa,*pb,*ch,*pc;
char c;
ch=(NODE*)malloc(sizeof(NODE));
pc=ch;
pa=ah;
pb=bh;
while(pa!=NULL&&pb!=NULL)
{
if(pa->exp==pb->exp)c='=';
else if(pa->exp>pb->exp)c='>';
else c='<';
switch(c)
{
case'=':
if(pa->coef+pb->coef!=0)
pc=insert(pc,pa->coef+pb->coef,pa->exp);
pa=pa->link;
pb=pb->link;
break;
case'>':
pc=insert(pc,pa->coef,pa->exp);
pa=pa->link;
break;
case'<':
pc=insert(pc,pb->coef,pb->exp);
pb=pb->link;
break;
}
}
while(pa!=NULL)
{
pc=insert(pc,pa->coef,pa->exp);
pa=pa->link;
}
while(pb!=NULL)
{
pc=insert(pc,pb->coef,pb->exp);
pb=pb->link;
}
pc->link=NULL;
pc=ch;
ch=ch->link;
free(pc);
return(ch);
}
void print(NODE *head)
{
NODE*p=NULL;
p=head;
while(p!=NULL)
{
printf("%d%d\n",p->coef,p->exp);
p=p->link;
}
}
int main(void)
{
ah=creat();
bh=creat();
ch=polyadd_l(ah,bh);
print(ch);
}