每次运行此循环时,我都会在循环的第二次迭代中遇到段错误。
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时,它显示段错误。
最佳答案
执行temp = new1->next;
后,如果new1
是最后一个,temp
可能为NULL
列表的节点。虽然 temp
为 NULL
,但当您访问此行中的字段时,它会引发段错误 printf("Temp var : %d\n",temp->数据);
关于c - 对链表进行排序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843655/