我正在执行管理c中的链表的功能,并且我在使用删除函数时遇到了问题。 这只获取指向链表和值的指针,并删除具有该值的第一个节点。问题是,如果我传递一个空列表,我会得到一个分段错误。知道吗?
sll_node *sll_remove(sll_node *list, int search_value)
{
sll_node* head = list;
sll_node* delete = list->next;
if(head == NULL)
{
return list;
}
if(head != NULL && head->value == search_value)
{
list = head->next;
free(head);
return list;
}
while(delete)
{
if(search_value == delete->value)
{
head->next = delete->next;
free(delete);
return list;
}
head = head->next;
delete = delete->next;
}
return list;
}
在取消引用之前,您需要检查list
是否为 null
sll_node *sll_remove(sll_node *list, int search_value)
{
if(!list){
return list;
}
sll_node* head = list;
sll_node* delete = list->next;
if(!head)
{
return list;
}
if(head && head->value == search_value)
{
list = head->next;
free(head);
return list;
}
while(delete)
{
if(search_value == delete->value)
{
head->next = delete->next;
free(delete);
return list;
}
head = head->next;
delete = delete->next;
}
return list;
}