delete tail 不 return 正确的列表

delete tail doesn't return the correct list

我在删除尾部函数时遇到了一些问题,当我释放当前节点时它不起作用,但是当我使用下一个节点时一切正常。有人可以向我解释发生了什么以及为什么它不起作用吗?

这是列表

    typedef struct node {
    int codice;
    struct node *next;
} nodo;

typedef nodo * lista;

不工作的删除尾功能是

lista rimuovi_in_coda(lista l){
    if(l == NULL) return NULL;
    lista l_scorri = l;
    while(l_scorri->next != NULL)
        l_scorri = l_scorri->next;

    free(l_scorri);
    l_scorri = NULL;
    return l;
}

在此列表 l 未修改:

input: 0, 4
output: 0, 4

工作的是:

lista rimuovi_in_coda(lista l){
    if(l == NULL || l->next == NULL) {
        free(l);
        return NULL;
    }
    lista l_scorri = l;
    while(l_scorri->next->next != NULL)
        l_scorri = l_scorri->next;

    free(l_scorri->next);
    l_scorri->next = NULL;
    return l;
}

在此返回的列表符合预期

input: 0, 4
output: 0

您永远不会重置任何指针或将任何节点的 "next" 设置为 NULL。您只是 free 一个元素,但将其留在列表中。

在第一个函数中,您正在更改局部变量 l_scorri

free(l_scorri);
l_scorri = NULL;

这不会更改前面节点的数据成员 next 的值。

在第二个程序中,您确实更改了前面节点的下一个数据成员。

l_scorri->next = NULL;

函数可以写得简单一点。例如

#include <stdio.h>
#include <stdlib.h>

typedef struct node 
{
    int codice;
    struct node *next;
} nodo;

typedef nodo * lista;

int rimuovi_in_coda( lista *l )
{
    int success = *l != NULL;

    if ( success )
    {
        while ( ( *l )->next != NULL ) l = &( *l )->next;

        free( *l );
        *l = NULL;
    }

    return success;
}

int main( void )
{
}