【发布时间】:2019-03-17 04:20:26
【问题描述】:
我正在使用 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为空,list->next会崩溃。您需要在此声明之前进行检查。 -
是的,这就是问题所在,谢谢!就像在c中一样,我不能在语句之前移动检查,所以我将delete设置为NULL,然后给出值。再次感谢谢尔盖
-
您可以使用三元运算符并这样说:
sll_node* delete = (list == NULL) ? NULL : list->next; -
“因为它在 c 中,我不能在语句之前移动检查”是什么让你无法使用 C99 或更高版本??
标签: c linked-list