c - 对链表进行排序时出现分段错误
问题描述
所以这是我的排序功能,我不是交换链表中的信息,只是交换下一个节点的指针。我有一个类似的功能,可以按完美运行的汽车价格排序,当我使用按汽车年份排序时,我得到分段错误 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”变量排序。
解决方案
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
}
希望此代码段能满足您的要求
推荐阅读
- python - 当我杀死python进程时,输出文件为空
- php - TypeError:“无法将字符串转换为 ByteString,因为索引 519 处的字符的值 8230 大于 255。”
- python - 对多索引熊猫系列中的重复行求和,并为缺失的类别插入零
- python - 如何在终端中修复“pyuic5:找不到命令”
- django-models - 如何过滤存储在 django char 字段中的日期
- c# - 基于令牌的身份验证:注册
- javascript - Vue.js在悬停时更改子组件的css样式
- android - 为 RecyclerView 下载图像的性能问题
- asp.net - 从网站 URl 中删除虚拟目录名称
- java - java中的所有类都属于Object Class,那么为什么一个类不能是静态的