Deleting node inside of linked list

南笙酒味 提交于 2021-01-28 13:46:23

问题


I'm stuck on this particular function that frees all even nodes from the linked list. I've figured out how to free all the nodes from a linked list but I cannot figure this out. The code i'm posting is very wrong. What I don't understand is how to use a node *temp variable and link it to the head->next node, as the head is what is being freed (because it is even). Also, at the end of the while loop, I know that I need to increment to the next node in the list, but I seem to be doing that already in the first if statement, so wouldn't calling current = current->next actually be taking me to current->next->next, and skipping a node? Sorry for this massive block of text.

node *delete_even_node(node *head)
{
    node *temp, *current = head;
    if (head == NULL)
        return NULL;
    while (current != NULL)
    {
        if (current->data % 2 == 0)
        {
            printf("Deleting Even %d\n", current->data);
            temp = current->next; //problem starts
            temp = temp->next;
            free(temp);
        }
        else
            current = current->next;
        current = current->next; 
    }
    return head;
}

回答1:


There are two approaches.

If to use your approach when the pointer to the head node is passed by value then the function can look the following way.

node * delete_even_node( node *head )
{
    while ( head && head->data % 2 == 0 )
    {
        node *tmp = head;
        head = head->next;
        free( tmp );
    }

    if ( head )
    {
        node *current = head;
        while ( current->next )
        {
            if ( current->next->data % 2 == 0 )
            {
                node *tmp = current->next;
                current->next = current->next->next;
                free( tmp );
            }
            else
            {
                current = current->next;
            }
        }
    }

    return head;
}

Another approach is to pass the pointer to the head node by reference.

For example

void delete_even_node( node **head )
{
    while ( *head )
    {
        if ( ( *head )->data % 2 == 0 )
        {
            node *tmp = *head;
            *head = ( *head )->next;
            free( tmp );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}

And the function is called like

delete_even_node( &head );


来源:https://stackoverflow.com/questions/64527206/deleting-node-inside-of-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!