【问题标题】:How to delete Nodes in linked list with zero value in c如何在c中删除链表中零值的节点
【发布时间】:2020-03-31 21:46:57
【问题描述】:

我正在使用 codeBlock,我正在尝试删除所有零值的节点 起初我删除了头节点,直到头中没有零值 像这样

void exo6(Node* head)
{
    Node* p=(Node*)malloc(sizeof(Node));
    p=head;
    head=p;
    if(p->data==0)
    {
        while(p->data==0)
        {
            head=p->next;
            free(p);
            p=head;
        }
    }
    head=p;

然后我继续像这样删除下一个节点

while(p!=null)
    {
        if(p->next->data==0)
        {
            Node* q=p->next;
            free(p->next);
            p->next=q->next;
        }else
            p=p->next;

    }
    printf("The NEw list is \n");
    display(head);

}

但代码只在头节点上工作

结果是这样的

【问题讨论】:

    标签: c data-structures struct linked-list singly-linked-list


    【解决方案1】:

    最简单的方法是当函数通过引用接受指向头节点的指针时。

    你来了。

    void exo6( Node **head )
    {
        while ( *head != NULL )
        {
            if ( ( *head )->data == 0 )
            {
                Node *current = *head;
                *head = ( *head )->next;
                free( current );
            }
            else
            {
                head = &( *head )->next;
            }
        }
    }
    

    像这样调用函数

    exo6( &head )l
    

    至于你的函数实现,那么它从内存泄漏开始

    void exo6(Node* head)
    {
        Node* p=(Node*)malloc(sizeof(Node));
        p=head;
        // ...
    

    首先分配内存并将其地址存储在指针p 中,然后立即重新分配指针。还要考虑到,当指向头节点的指针等于 NULL 时,通常可以调用该函数。 此外,该函数按值接受指向头节点的指针。因此该函数处理原始指针的副本。更改副本不会影响原始指针。

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 1970-01-01
      • 2016-01-02
      • 2016-03-02
      • 1970-01-01
      • 2014-04-02
      • 2022-01-08
      • 2017-10-21
      相关资源
      最近更新 更多