编写时出现的问题:
1.没有充分理解结构体的定义,无法正确使用
2.addlist() 函数中,未申请空间而直接使用导致无法访问
3.理解相加过程的思路
代码部分:
#include <stdio.h>
#include <malloc.h>
typedef struct polynode{
int coef;//系数
int exp;//指数
struct polynode *next;
}polynode,*list;
list creatlist(int l);
void printlist(list poly);
list addlist(list polya,list polyb);
int main()
{
list polya,polyb,polyc;//定义多项式,polyc为所求多项式和
int la,lb;//定义多项式项数
printf("The first polynode length : ");
scanf("%d",&la);
polya=creatlist(la);
printf("The first polynode : P1(X) = ");
printlist(polya);
printf("\n");
printf("The second polynode length : ");
scanf("%d",&lb);
polyb=creatlist(lb);
printf("The second polynode : P2(X) = ");
printlist(polyb);
printf("\n");
printf("ADD\n");
printf("P1(X)+P2(X) = ");
polyc=addlist(polya,polyb);
printlist(polyc);
return 0;
}
list creatlist(int l)
{
list head,rear,s;//rear:用于尾插
int i,c,e;
head=(list )malloc(sizeof(struct polynode));
rear=head;
printf("Please enter the coef and exp : \n");
for(i=0;i<l;i++)
{
s=(list )malloc(sizeof(struct polynode));
scanf("%d %d",&c,&e);
s->coef=c;
s->exp=e;
rear->next=s;
rear=s;
}
rear->next=NULL;
return head;
}
void printlist(list poly)
{
list s;
s=poly->next;
while(s!=NULL)
{
printf("%dx^%d",s->coef,s->exp);
s=s->next;
if(s!=NULL)
if(s->coef>0)
printf("+");
else
printf("");
}
printf("\n");
}
list addlist(list polya,list polyb)
{
list p,q,tail,temp,newpoly;
int sum;
p=polya->next;
q=polyb->next;
newpoly=(list )malloc(sizeof(struct polynode));//应分配空间进行存储
tail=newpoly;
while(p!=NULL&&q!=NULL)
{
if(p->exp < q->exp)
{
tail->next=p;
tail=p;
p=p->next;
}
else if(p->exp == q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
tail->next=p;
tail=p;
p=p->next;
temp=q;
q=q->next;
free(temp);
}
else
{
temp=p;
p=p->next;
free(temp);
temp=q;
q=q->next;
free(temp);
}
}
else
{
tail->next=q;
tail=q;
q=q->next;
}
}
if(p!=NULL)
{
tail->next=p;
tail=p;
p=p->next;
}
else
{
tail->next=q;
tail=q;
q=q->next;
}
return newpoly;
}