Problem deleting list with recursion

1

I'm trying to use this function to remove it from the list, but it runs infinitely.

void rDeleta(lista* l, int elemento) {
    if(l!= NULL) {
        if(l->elem == elemento) {
            lista* aux = l;
            l = l->prox;
            free(aux);
        } else {
            rDeleta(l->prox, elemento);
        }
    }
}
    
asked by anonymous 06.12.2016 / 20:26

2 answers

1

I do not know how your function is running endlessly. The impression I have is that if this function gets stuck in an infinite loop it should stop sometime with a stackoverflow error.

Anyway, you might notice some of the wrong things in your implementation.

Let's look at the part where you are deleting the element. Assume we have a list A-> B-> C and you are trying to remove B. You are currently doing this with a l = l->prox :

antes:

       l ---\
            |
            v
[ A ] --> [ B ] --> [ C ]

depois de  l = l->prox:

                l ---\
                     |
                     v
[ A ] --> [ B ] --> [ C ]

However, the variable l is a local variable of the rDelete function and at no time did you change the value of the prox field of the "A" node in the list.

The simplest way to resolve this problem is to modify the rDeleta function instead of returning void, returning the pointer to the list head that is obtained by removing the elemento element from the l / p>

I think with this tip maybe you can solve your exercise.

    
06.12.2016 / 21:24
0

Usually only calls the method inside of itself when working with Graphs .

Since you are using a list, simply move on to the next element.

lista *rem;
while(l){
    rem = l;
    l = l->prox;

    free(rem)
}

This snippet clears the entire list.

lista *rem;
lista *prev = l;
while(l){
    if(elemento == l->elem){
        rem = l;
        l = l->prox;
        prev->prox = l;
        free(rem);
        break; // encerra o loop
    }else{
        prev = l;
        l = l->prox;
    }
}

This excerpt removes an item from the list

    
06.12.2016 / 20:34