c - 对链表进行排序时出现段错误

标签 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时,它显示段错误。

最佳答案

执行temp = new1->next;后,如果new1是最后一个,temp可能为NULL列表的节点。虽然 tempNULL,但当您访问此行中的字段时,它会引发段错误 printf("Temp var : %d\n",temp->数据);

关于c - 对链表进行排序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843655/

相关文章:

我们可以通过另一个包含我们希望指针指向的其他变量的地址的变量将地址分配给指针吗?

c - 即使使用 fflush 也会跳过 scanf

c - 关于linux中container_of宏的疑问

python - Apache Spark按用户ID排序分区,并将每个分区写入CSV

python - 排序二维列表python

c++ - 帮助确定所需的窗口对话框资源类型

c++ - 最小唯一字符

java - 就地在链表上实现自然归并排序,并且只交换来自节点的项目

java - Hibernate - 具有排序顺序的多列索引

python - 在列值和索引值上对 Pandas 数据框进行排序?