Am正在尝试删除给定字符串的所有出现。此代码删除一个节点,但保留所有其他节点。我试着把它绕一圈,但仍然没有效果。
我还想知道,是否有可能删除结构参数并使其发生。我试图删除它并修改代码,但我得到了一个分段错误。感谢您提前回答。
void deleteNode(struct node** head, char* searchName) {
struct node* current;
for(current=*head; current; current = current->next){
if (!strcmp(current->name, searchName))
{
if (current->next)
current->next->prev = current->next;
if (current->prev)
current->prev->next = current->prev;
if (current == *head)
*head = current->next;
current->prev = NULL;
current->next = NULL;
free(current);
return;
}
}
}
return
语句将在第一次命中后结束函数。此外,序列current->next = NULL; free(current); current = current->next
将在释放内存后访问内存,并将current设置为NULL。您可能需要在循环中更新current
,并使用一个额外的节点指针变量进行删除。
void deleteNode(struct node** head, char* searchName)
{
struct node* current;
struct node* to_delete;
for(current=*head; current;)
{
if (!strcmp(current->name, searchName))
{
to_delete = current;
current = current->next;
if (current) {
current->prev = to_delete->prev;
}
if (to_delete->prev) {
to_delete->prev->next = current;
}
if (to_delete == *head)
*head = current;
free(to_delete);
} else {
current = current->next;
}
}
}
您的函数错误。例如,如果语句
if (current->next)
current->next->prev = current->next;
应像一样重写
if (current->next)
current->next->prev = current->prev;
^^^^
功能可以通过以下方式声明和定义
void deleteNode( struct node **head, const char *searchName )
{
while ( *head )
{
if ( strcmp( ( *head )->name, searchName ) == 0 )
{
struct node *current = *head;
if ( current->next ) current->next->prev = current->prev;
*head = current->next;
free( current );
}
else
{
head = &( *head )->next;
}
}
}
请注意,如果结构struct node
的数据成员name
指向存储字符串的动态分配内存,则在为上述函数中的指针current
调用函数free
之前,必须释放为该字符串分配的内存。也就是说,您需要再添加一个类似的函数free
的调用
free( current->name );
free( current );
如果你有一个指向头节点的全局指针,例如head
,那么函数可以用以下方式定义
void deleteNode( const char *searchName )
{
struct node **head_ref = &head;
while ( *head_ref )
{
if ( strcmp( ( *head_ref )->name, searchName ) == 0 )
{
struct node *current = *head_ref;
if ( current->next ) current->next->prev = current->prev;
*head_ref = current->next;
free( current );
}
else
{
head_ref = &( *head_ref )->next;
}
}
}