所以我编写了一个插入,删除和显示已排序链表的程序。一切都运行顺利,但当我输入一个无效的数字(不在排序的链表中)进行删除时,我的程序崩溃了。这是我的删除功能: -
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;
}
Click here完整计划。提前谢谢!
答案 0 :(得分:3)
while
循环执行,直到help_ptr->next
为NULL
。在循环之后,您比较help_ptr->next->data
- 但由于help_ptr->next
为NULL
,它会崩溃。
最后if
基本上是不必要的。如果在while
循环期间未找到该项目,则该项目不在列表中。
答案 1 :(得分:0)
在遍历整个列表之后(正如你在while循环中所做的那样),你再次检查“if条件”中的下一个元素肯定会导致分段错误。如果元素是你,则从while循环中出来正在搜索未被发现欢迎您说“找不到元素”。