2010-12-09 31 views
2

與我之前發佈的帖子相關Editing a node in a Linked list。我已經做了在編輯節點以下步驟:編輯鏈接列表中的節點Part2

  1. 編輯目標節點數據
  2. 刪除目標節點
  3. 重新插入目標節點

的問題是,我不能再插入AT如下節點的TOP ....

std1 90 -> std 2 50 -> std3 20 -> NULL 

我編輯STD3到100,結果會是這樣

std2 50 -> std3 20 -> NULL 

總之,我不能把它放回頂層節點。重新插入除頂層節點以外的任何地方都可以正常工作。

+1

什麼不起作用?插入錯誤位置,未插入,其他條目丟失,分段錯誤,...? – 2010-12-09 17:12:47

+0

如果您插入與另一個年級相同的學生,則會中斷。 insert_student中的while循環不會執行,因此對prev_std-> next的賦值將失敗,因爲prev_std仍然爲NULL。 insert_student中的其中一個條件需要包含「=」以及小於或大於 – 2010-12-09 17:17:29

回答

1

如果頭節點爲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;