为什么我的删除搜索链表功能不起作用?

why does my delete search linked list function not working?

我在使用这个函数时遇到了这个问题,我想删除所有具有给定字符串的节点,但是当我运行在我的程序中使用它时,它从第一个 find char ex[] 中删除了所有节点,我是 c 的新手,请指导我

void delSearch(char ex[]){
    int del;
    struct file *temp = head;
    while(temp!=NULL){
        if(strcmp(temp->ex,ex)==0){
            file *temp2 = temp->next;
            file *temp3 = temp;
            temp->next=temp2;
            free(temp3);
            temp3 = NULL;
        }
        else
        {
        temp = temp->next;
        }
    }
}

对于初学者来说,局部变量 del

int del;

未在函数内使用。

该函数不会更改全局指针 head,前提是它指向存储给定字符串的节点。

您还需要更新要删除的节点之前的节点的数据成员next

函数如下所示。

void delSearch( const char ex[] )
{
    while ( head && strcmp( head->ex, ex ) == 0 )
    {
        struct file *tmp = head;
        head = head->next;
        free( tmp );
    }
    
    if ( head )
    {
        for ( struct file *current = head; current->next != NULL; )
        {
            if ( strcmp( current->next->ex, ex ) == 0 )
            {
                struct file *tmp = current->next;
                current->next = current->next->next;
                free( tmp );
            }
            else
            {
                current = current->next;
            }
        }
    }
}   

如果想知道调用函数后删除了多少个节点,函数可以改成下面的方式。

size_t delSearch( const char ex[] )
{
    size_t total = 0;
    
    while ( head && strcmp( head->ex, ex ) == 0 )
    {
        struct file *tmp = head;
        head = head->next;
        free( tmp );
        ++total;
    }
    
    if ( head )
    {
        for ( struct file *current = head; current->next != NULL; )
        {
            if ( strcmp( current->next->ex, ex ) == 0 )
            {
                struct file *tmp = current->next;
                current->next = current->next->next;
                free( tmp );
                ++total;
            }
            else
            {
                current = current->next;
            }
        }
    }
    
    return total;
}   

另一种函数定义可以如下所示

size_t delSearch( const char ex[] )
{
    size_t total = 0;
    
    for ( struct file **current = &head; *current != NULL; )
    {
        if ( strcmp( ( *current )->ex, ex ) == 0 )
        {
            struct file *tmp = *current;
            *current = ( *current )->next;
            free( tmp );
            ++total;
        }
        else
        {
            current = &( *current )->next;
        }
    }
    
    return total;
}