[英]Deleting a node in a sorted linked list in C
所以我編寫了一個插入,刪除和顯示已排序鏈表的程序。 一切都運行順利,但當我輸入一個無效的數字(不在排序的鏈表中)進行刪除時,我的程序崩潰了。 這是我的刪除功能: -
struct node* remove(struct node* head_ptr, int target)
{
struct node* help_ptr, *node2del;
help_ptr = head_ptr;
if(help_ptr != NULL)
{
if(help_ptr -> data == target)
{
head_ptr = help_ptr -> next;
free(help_ptr);
return head_ptr;
}
while (help_ptr -> next != NULL)
{
if(help_ptr -> next -> data == target)
{
node2del = help_ptr -> next;
help_ptr -> next = help_ptr -> next -> next;
free(node2del);
return head_ptr;
}
help_ptr = help_ptr -> next;
}
if(help_ptr->next->data != target)
printf("\n%d is not in the list.",target);
}
return head_ptr;
}
單擊此處查看完整計划。 提前致謝!
你的while
循環執行,直到help_ptr->next
為NULL
。 在循環之后,你比較help_ptr->next->data
- 但是當help_ptr->next
為NULL
,它會崩潰。
最后一個if
基本上是不必要的。 如果在while
循環期間未找到該項目,則該項目不在列表中。
在遍歷整個列表之后(正如你在循環中所做的那樣),你再次檢查“if條件”中的下一個元素肯定會導致分段錯誤。如果你正在搜索的元素是沒有發現你歡迎說“找不到元素”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.