Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在c语言中删除零值链表中的节点_C_Data Structures_Struct_Linked List_Singly Linked List - Fatal编程技术网

如何在c语言中删除零值链表中的节点

如何在c语言中删除零值链表中的节点,c,data-structures,struct,linked-list,singly-linked-list,C,Data Structures,Struct,Linked List,Singly Linked List,我正在使用代码块,我正在尝试删除所有零值的节点 首先,我删除了head节点,直到head中没有零值为止 那样 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;

我正在使用代码块,我正在尝试删除所有零值的节点 首先,我删除了head节点,直到head中没有零值为止 那样

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

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

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

}
但是代码只在头部节点上起作用


结果如下

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

给你

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
中,然后立即重新分配指针。还要考虑到,通常当指向head节点的指针等于NULL时,可以调用该函数。 此外,该函数通过值接受指向头部节点的指针。因此,该函数处理原始指针的副本。更改副本不会影响原始指针