[英]Sort a linked list changing pointer's values
我正在嘗試編寫代碼來更改指針值的鏈表。當我到達最后一個節點時,程序崩潰.searchMinor函數運行正常,問題出在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
}
}
您正在sortList
中獲取nbegin
的本地副本。 因為您要返回本地副本,所以這是未定義行為的原因。 相反,您必須傳遞它的地址。 喜歡,
// edit the function according to the signature
t_list *searchMinor(t_nodeL **n);
// and call like in sortList
searchMinor(&nbegin)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.