[英]Deleting a structure from a doubly linked list based on its contents (in C)
我的程序是一個基本的C接口,允許用戶輸入,向前打印,向后打印以及從列表中刪除MP3記錄。 該列表以C語言形式實現為MP3結構的雙向鏈接列表。
除Delete之外,我所有的功能都可以正常工作。 Delete帶有指向列表頭節點的指針和一個字符串,表示您要刪除哪個藝術家的記錄。 在我的主筆錄中,我記錄了用戶輸入,並確認它已正確記錄。 然后,我將用戶輸入和主要參考傳遞到以下函數中,以刪除所述MP3記錄。 但是,我的程序可以正常構建和執行,但是在調用delete函數時實際上並沒有刪除任何記錄。 任何幫助表示贊賞。
為了清楚起見,我已經查看了堆棧上有關從DLL刪除節點的多個問題,但是它們都與持有整數值的簡單DLL有關,並且似乎不適用於我的情況。 如果這是一個重復的問題,我深表歉意。如果是的話,請指出我要重復的問題。 再次感謝您的協助。 下面是我的功能
void deleteMP3(struct MP3* head_ref, char* artist)
{
//Declaring a temp struct to hold the node that needs to be deleted
struct MP3* temp;
//Check if the head node contains the artist to be deleted
if(head_ref->artist == artist)
{
//Set temp to the current head ref so it can be deleted
temp = head_ref;
//Set head_ref to the next node in the list
head_ref = head_ref->next;
//Free the memory associated with the MP3 to be deleted
free(temp->artist);
free(temp->title);
free(temp->date);
free(temp);
}
//Traverse the list checking each MP3's artist field
while(head_ref != NULL)
{
//Check the artist of the current MP3 against the input. Delete it if it needs to be deleted
if(head_ref->artist == artist)
{
//Set temp to the current MP3
temp = head_ref;
//Check if the MP3 is the last MP3. If not, change the field of the next node in the list
if(head_ref->next != NULL)
{
//Sets the previous field of the next node in the list to the previous field of the node to be deleted
head_ref->next->prev = head_ref->prev;
}
//Change the next pointer of the previous MP3 in the list to the MP3 following the one to be deleted
head_ref->prev->next = head_ref->next;
//Free the memory
free(temp->artist);
free(temp->title);
free(temp->date);
free(temp);
}
//Traverse forward
head_ref = head_ref->next;
}
}
代碼中有一些問題,但以下兩個是最關鍵的問題:
1.)使用strcmp
比較字符串。 head_ref->artist == artist
比較指針,而不是內容,並且通常不太可能傳遞DLL元素指向的指針。
2.)如果頭部被刪除,則需要將“新”頭部傳遞回deleteMP3
的調用方; 否則,傳遞給deleteMP3
的變量仍將保留指向(已刪除)節點的指針。 因此將void deleteMP3(struct MP3* head_ref, char* artist)
更改為struct MP3 *deleteMP3(struct MP3* head_ref, char* artist)
並返回DLL的實際頭(無論是否更改)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.