Im trying to make a code to sort a linked list changin the pointers value.The program crashes when i get to the last node.The searchMinor functions works fine, the problem is in the logic of sortList.
typedef struct{
int num;
}t_dataL;
typedef struct s_nodeL{
t_dataL dataL;
struct s_nodeL *next;
}t_nodeL;
typedef t_nodeL *t_list;
t_list *searchMinor(t_nodeL*n){
t_list *min=&n, *l=&n;
l=&(*l)->next;
while(*l) {
if( (*l)->dataL.num < (*min)->dataL.num )min=l;
l=&(*l)->next;
}
return min;
}
void sortList(t_list *l){
t_nodeL *nbegin=*l; //save the beginig of the list in nbegin
t_list *plec,*aux;
plec=searchMinor(nbegin); //search the minor from the begining
*l=*plec; //put as the first elemnet on the list the fisrt minor value
while(nbegin->next){
aux=&(*plec)->next; //Save the value of the next of the minor in aux
*plec=*aux; //remove the minor from the list
plec=searchMinor(nbegin); //search the new minor from the begining of the list
*aux=*plec; //the next of the old minor is the new minor
}
}
You are obtaining the local copy of nbegin
in sortList
. Because you are returning local copy, it is the reason of undefined behaviour . Instead, you have to pass the address of it. Like,
// edit the function according to the signature
t_list *searchMinor(t_nodeL **n);
// and call like in sortList
searchMinor(&nbegin)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.