[英]bubble sort linked list in C
我正在嘗試為 C 中的單鏈表編寫冒泡排序函數。不知道為什么 sort_list 有效但 sort_list1 無效。
當我使用 sort_list1 時,它返回“發生異常。EXC_BAD_ACCESS (code=1, address=0x0)”。
感謝您對此的幫助。 謝謝你。
typedef struct list{int data; struct list *next;} list;
list *compare_sort(list *h){ //compare and swap function for bubble sort
if ((h -> data) > (h -> next -> data)){
list *temp = h;
h = h -> next;
temp -> next = h -> next;
h -> next = temp;
}
return h;
}
list *sort_list(list *h){ //to bubble sort the list
int i, j;
list *h_temp;
for (i = 0; i < N-2; i++) {
h = compare_sort(h);
h_temp = h;
for (j = 0; j < N-2-i; j++) {
h_temp -> next = compare_sort(h_temp -> next);
h_temp = h_temp ->next;
}
}
return h;
}
list *sort_list1(list *h){ //to bubble sort the list
int i, j;
list *h_temp;
for (i = 0; i < N-2; i++) {
h_temp = h;
for (j = 0; j < N-2-i; j++) {
h_temp = compare_sort(h_temp);
h_temp = h_temp ->next;
}
}
return h;
}
對於初學者來說,當函數sort_list
和sort_list1
依賴於全局變量N
時,這是一種不好的方法。
至於函數sort_list1
則有兩個問題,其原因是處理指針h
的值的副本和存儲在數據成員next
中的指針的值。
h_temp = h;
//...
h_temp = compare_sort(h_temp);
h_temp = h_temp ->next;
例如,更改最初存儲指針h
值副本的指針h_temp
不會反映存儲在原始指針h
中的值。 它保持不變。
數據成員next
的值也存在相同的問題,因為更改了存儲數據成員next
值的副本的相同指針h_temp
(其值),而不是更改數據成員next
本身的值。
與函數sort_list1
中的函數sort_list
,更改了原始指針h
和數據成員next
的值
h = compare_sort(h);
h_temp -> next = compare_sort(h_temp -> next);
請注意,最好將節點的比較和它們的交換分開,而不是將它們放在一個函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.