【问题标题】:Deleting node inside of linked list删除链表内的节点
【发布时间】:2021-02-08 02:59:18
【问题描述】:

我被困在这个从链表中释放所有偶数节点的特殊功能上。我已经想出了如何从链表中释放所有节点,但我无法弄清楚。我发布的代码非常错误。我不明白的是如何使用 node *temp 变量并将其链接到 head->next 节点,因为 head 是被释放的(因为它是偶数)。此外,在 while 循环结束时,我知道我需要递增到列表中的下一个节点,但我似乎已经在第一个 if 语句中这样做了,所以不会调用 current = current->next实际上是带我到 current->next->next,然后跳过一个节点?抱歉,有这么大的文字块。

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

【问题讨论】:

  • 这会产生很多结果。这些都没有帮助吗? stackoverflow.com/search?q=%5Bc%5D+delete+node+linked+list
  • 删除节点是不够的。您还必须更新指向已删除节点的指针,即前一个节点的头或next 字段。
  • @klutt 啊,是的,你是对的。我发现了一些需要做更多挖掘的事情。
  • 而你想删除current,而不是它后面两个地方的节点。 (如果current->next == NULL,赋值temp = temp->next会崩溃。)

标签: c linked-list nodes free singly-linked-list


【解决方案1】:

有两种方法。

如果在指向头节点的指针按值传递时使用您的方法,则函数可以如下所示。

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

另一种方法是通过引用将指针传递给头节点。

例如

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

函数的调用方式如下

delete_even_node( &head );

【讨论】:

  • 你能快速解释一下第一种方法中的 if (head) 语句吗?这会一直执行吗?
  • @idkusrname126 if ( head ) 与 if( head != NULL ) 相同
  • @idkusrname126 在第一个函数中有一个错字。 while 循环看起来像 while (head && head->data % 2 == 0)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 2019-05-10
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多