如果頭節點爲97%,並且您傳遞的節點爲97%,則會出現問題。你需要說
while (curr_std != NULL && to_add->grade <= curr_std->grade){
您也將有一個問題,如果您正在編輯的學生是第一個節點,因爲這:
while((cur != NULL) && (strcmp(cur->name,temp) != 0)){
將評估爲真,
prev = cur;
將永遠不會被調用,而留下prev
= null。然後當你到達
prev->next = cur->next;
你有一個空引用。您需要明確地測試添加到頭節點;這是它自己的特殊情況。
scanf("%d", &(cur->grade));
if (prev == null) { // you matched the head
head = cur->next;
}
else {
prev->next = cur->next;
}
編輯
當您添加了頭,在你的代碼,您沒有設置頭指向您的新節點。您將返回舊頭,該頭現在指向列表中的第二個節點。試試:
while (curr_std != NULL && to_add->grade < curr_std->grade){
prev_std = curr_std;
curr_std = curr_std->next;
}
// if you're adding to the head, you didn't go into the above loop
// curr_std is still pointing to head in this case
if (curr_std == head) {
head = to_add
}
else {
prev_std->next = to_add;
}
to_add->next = curr_std;
return head;
什麼不起作用?插入錯誤位置,未插入,其他條目丟失,分段錯誤,...? – 2010-12-09 17:12:47
如果您插入與另一個年級相同的學生,則會中斷。 insert_student中的while循環不會執行,因此對prev_std-> next的賦值將失敗,因爲prev_std仍然爲NULL。 insert_student中的其中一個條件需要包含「=」以及小於或大於 – 2010-12-09 17:17:29