我不确定我是否听起来很笨,但仍然......我想使用链接列表开发一个程序,我可以添加5个多项式。我能提出的代码是......
struct node
{
int exp,coeff;
struct node *next;
} *start[5]={NULL};
void read()
{
struct node *current,*newnode;
int n,i,max,j;
printf("How many poly?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nDetails of poly %d\n",i);
printf("Max degree:");
scanf("%d",&max);
for(j=max;j>=0;j--)
{
newnode=(struct node *)malloc(sizeof(newnode));
printf("\nEnter coeff of %d:",j);
scanf("%d",&newnode->coeff);
newnode->exp=j;
if(start[i]==NULL)
{
printf("a%d",start[i]);
start[i]=newnode;
newnode->next=NULL;
printf("%d,%d",start[i],start[i]->next);
}
else if(start[i]->next==NULL)
{
printf("b");
start[i]->next=newnode;
newnode->next=NULL;
printf("%d",start[i]);
}
else
{
printf("c");
current=start[i];
while(current->next!=NULL)
current=current->next;
current->next=newnode;
newnode->next=NULL;
printf("%d",start[i]);
}
}
}
}
void sum()
{
struct node *curr1,*curr2,*tmp;
int i,co,ex;
curr1=start[0];
while(curr1!=NULL)
{
for(i=1;i<5;i++)
{
co=0;
if(curr1==start[i])
tmp=start[i];
else
tmp=tmp->next;
curr2=tmp;
if(curr1->exp==curr2->exp)
{
if(co==0)
co=co+curr1->coeff+curr2->coeff;
else
co=co+curr2->coeff;
ex=curr1->exp;
break;
}
else if(curr1->exp>curr2->exp)
{
ex=curr1->exp;
if(co==0)
co=co+curr1->coeff;
else
break;
}
else
{
ex=curr2->exp;
if(co==0)
co=co+curr2->coeff;
else
break;
}
}
printf("%dX^%d",co,ex);
curr1=curr1->next;
}
}
int main()
{
read();
printf("result:\n");
sum();
getch();
return 0;
}
但是在执行时,只有第一个多项式得到read.ie,'i'循环只工作一次。我试着检查我的阅读功能,注意第二个条件不起作用。这个,这个:
else if(start[i]->next==NULL)
{
printf("b");
start[i]->next=newnode;
newnode->next=NULL;
printf("%d",start[i]);
}
打印b是检查程序是否进入此块LOL。 有人帮我这个... ...
答案 0 :(得分:1)
这部分
newnode=(struct node *)malloc(sizeof(newnode)); // This will allocate space for
// a pointer to struct node
应该是
newnode=(struct node *)malloc(sizeof(struct node)); // This will allocate space for
// a struct node
或更好,如@chux
所示newnode = malloc(sizeof *newnode); // This will allocate space for
// whatever newnode points to. In
// this case a struct node
不确定它会有所作为,但我会改变:
start[5]={NULL};
到
start[5]={NULL, NULL, NULL, NULL, NULL};