删除链表中的节点 [英] Deleting node inside of linked list

查看:72
本文介绍了删除链表中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了这个特殊的功能,该功能从链接列表中释放了所有偶数节点.我已经找到了如何从链表中释放所有节点的方法,但是我无法弄清楚.我发布的代码是非常错误的.我不明白的是如何使用节点* temp变量并将其链接到head-> next节点,因为head是释放的对象(因为它是偶数).另外,在while循环结束时,我知道需要增加到列表中的下一个节点,但是我似乎已经在第一个if语句中进行了此操作,因此不会调用current = current->.接下来实际上是要带我进入current-> next-> next,然后跳过一个节点?对不起,这段文字如此庞大.

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;
}

推荐答案

有两种方法.

如果在通过值传递指向头节点的指针时使用您的方法,则该函数可以采用以下方式.

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.

例如

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 );

这篇关于删除链表中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆