2016-08-24 74 views
0

指示:執行以下功能按姓氏搜索,然後從鏈接列表中刪除第一個匹配的學生。如果找到了匹配的學生,該函數返回一個指向新鏈接列表頭的指針;如果找不到匹配的學生,則該列表不變,並返回鏈接列表的頭部。根據匹配的數據刪除節點

編譯並運行該代碼時,每次只刪除頭節點。即使名稱在列表中間或根本不在列表中,始終刪除頭節點。不確定發生了什麼問題。任何幫助將不勝感激!謝謝!

STUDENT *DeleteByLastName(STUDENT *students, char *name) 
{ 
struct STUDENT* current = students; 
struct STUDENT* previous = NULL; 

while (current != NULL) { 
    if (current->Lastname == name) { 
    if (previous == NULL) { 
     current = current->Next; 
     free(students); 
     students = current; 
    } 
    else { 
     previous->Next = current->Next; 
     free(current); 
     current = previous->Next; 
    } 
    } 
    else { 
    previous = current; 
    current = current->Next; 
    } 
    return current; 
}  
return NULL; 

} 
+9

'current-> Lastname == name' - 這不是比較字符串的方式。使用'strcmp'家族。這使我懷疑你在沒有顯示的功能中有類似的問題... –

+0

提示; 'char * name'應該是'const char * name',因爲你不會修改'name'指向哪個。 – ikegami

回答

0

感謝您的提示!這是我爲任何感興趣的人工作的代碼。

STUDENT *DeleteByLastName(STUDENT *students, char *name) 
{ 
struct STUDENT* current; 
struct STUDENT* head = students; 

current = students; 
int count = 0; 
struct STUDENT* previous = NULL; 

while (current != NULL) { 
    //check for matching head and delete 
    if (strcmp(current->Lastname,name) == 0 && count == 0) { 
     students = current->Next; 
     return students; 
    } 
    //If name matches but is not at the beggining of the list 
    if(strcmp(current->Lastname,name) == 0) { 
     previous->Next = previous->Next->Next; 
     current = current->Next; 
     return students; 
    } 
    else { 
     previous = current; 
     current = current->Next; 
     ++count; 
    } 
} 
return head; 
}