简体   繁体   English

delete tail不会返回正确的列表

[英]delete tail doesn't return the correct list

I'm having some issues with the delete tail function, It does not work when I'm freeing the current node, but when I work with the next node everything works fine. 我在删除尾部函数时遇到了一些问题,当我释放当前节点时它不起作用,但是当我使用下一个节点时,一切正常。 Can someone explain to me what is happening and why it does not work? 有人可以向我解释发生了什么以及为什么它不起作用?

this is the list 这是清单

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

typedef nodo * lista;

the delete tail function which does not work is 删除尾部功能不起作用

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

in this one the list l is not modified: 在这一个中,列表l未被修改:

input: 0, 4
output: 0, 4

the working one is: 工作的是:

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

in this one the list returned is as expected 在这一个中,返回的列表是预期的

input: 0, 4
output: 0

You never reset any pointers or set any node's "next" to NULL. 您永远不会重置任何指针或将任何节点的“下一个”设置为NULL。 You just free an element but leave it in the list. 您只需free一个元素,但将其保留在列表中。

In the first function you are changing the local variable l_scorri 在第一个函数中,您正在更改局部变量l_scorri

free(l_scorri);
l_scorri = NULL;

This does not change the value of the data member next of the preceding node. 这不会更改前一个节点的next数据成员的值。

In the second program you are indeed changing the data member next of the preceding node. 在第二个程序中,您确实正在更改前一个节点的下一个数据成员。

l_scorri->next = NULL;

The function can be written simpler. 该函数可以写得更简单。 For example 例如

#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 )
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM