首页 > 解决方案 > 对链表进行排序时出现分段错误

问题描述

所以这是我的排序功能,我不是交换链表中的信息,只是交换下一个节点的指针。我有一个类似的功能,可以按完美运行的汽车价格排序,当我使用按汽车年份排序时,我得到分段错误 11。

void ordenaCrescenteAno(ELEMCAR *iniLista){
  ELEMCAR *aux1 = NULL;
  ELEMCAR *aux2 = NULL;
  ELEMCAR *maior = NULL;
  ELEMCAR *troca = NULL;

  if(iniLista == NULL){
    printf("Lista Vazia\n");
    return;
  }

  for(aux1 = iniLista; aux1 != NULL; aux1 = aux1 -> seguinte){
    maior = aux1;
    for(aux2 = aux1; aux2 != NULL; aux2 = aux2 -> seguinte){
       if(aux2->info.ano > maior->info.ano){
          maior = aux2;
       }
    }
    if(maior != aux1){
      troca->seguinte = aux1->seguinte;
      aux1->seguinte = maior->seguinte;
      maior->seguinte = troca->seguinte;
    }

 }
}

我将把链表的详细信息放在这里:

typedef struct carro{
    char matricula[7];
    char marca[30];
    char modelo[30];
    int ano;
    char classe[30];
    float preco;
    char combustivel[10];
    int dataInspecao;
    int dataRevisao;
    char observacoes[100];
    int estado;
}CARINFO;

typedef struct CarElem{
    CARINFO info;
    struct CarElem *seguinte;
}ELEMCAR;

我究竟做错了什么?我无法弄清楚,因为我有一个类似的功能,但我正在按“preco”变量排序。

标签: csortingpointerslinked-list

解决方案


troca被初始化为 null 所以troca->sequinte会出错

改用这个

struct CarElem *troca; replace troca definition

troca = aux1->sequinte; replace troca->sequinte line with this
maior->sequinte = troca; remove ->sequinte from troca

我意识到上面的代码片段有问题。

在你的交换部分

if (maior != aux1)
{
  CARINFO carswap = aux1->info; // Copy the info into a temporary variable
  aux1->info = maior->info;     // Move info from maior to aux1
  maior->info = carswap;        // Move info from temporary variable to maior
}

希望此代码段能满足您的要求


推荐阅读