每次运行此循环时,我都会在循环的第二次迭代中遇到分段错误。
node *new,*new1;
new=(node*) malloc(sizeof(node));
new1=(node*) malloc(sizeof(node));
new = start->next;
for(;new->next != NULL;new = new->next)
{
for(new1=new->next;new1 != NULL;new1=new1->next)
{ //printf("LOOP\n");
if(new->data > new1->data)
{
printf("\n Swapping - new:%d and new1:%d\n",new->data,new1->data);
temp = (node*) malloc(sizeof(node));
temp1 = (node*) malloc(sizeof(node));
temp1 = new->next;
temp = new1->next;
new->next = temp;
printf("Temp var : %d\n",temp->data);
printf("Temp1 var : %d\n",temp1->data);
new1->next = new;
new1 = new;
new = temp1;
printf("After swapping , new:%d and new1 : %d\n",new->data,new1->data);
// free(temp);
// free(temp1);
}
}
}
每当我给它一个列表 - 例如。 4,1,9,6 它只交换4和1,当它是交换9和6的迭代时,它显示和分段错误。
答案 0 :(得分:0)
执行temp = new1->next;
后,如果temp
是列表的最后一个节点,则NULL
可能为new1
。虽然temp
为NULL
,但当您访问此行的printf("Temp var : %d\n",temp->data);