在分类链表时获取分段错误

时间:2017-10-20 06:41:39

标签: c sorting

每次运行此循环时,我都会在循环的第二次迭代中遇到分段错误。

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的迭代时,它显示和分段错误。

1 个答案:

答案 0 :(得分:0)

执行temp = new1->next;后,如果temp是列表的最后一个节点,则NULL可能为new1。虽然tempNULL,但当您访问此行的printf("Temp var : %d\n",temp->data);

字段时会出现细分错误
相关问题