Problem deleting from recursion list

Asked

Viewed 37 times

1

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

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

2 answers

1


I don’t know how your function is running endlessly. The impression I get is that if this function gets stuck in an infinite loop it should stop at some point with a stackoverflow error.

Anyway, you can see some things wrong in its implementation.

Let’s look at the part where you’re deleting the element. Assume that we have an A->B->C list and you are trying to remove B. Currently you are 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 rDeleta function and at no time you changed the value of the field prox of node "A" of the list.

The simplest way to solve this problem is to modify the function rDeleta for instead of returning void, return the pointer to the head of the list that is obtained by removing the element elemento of the list l.

I think with this tip you might be able to solve your exercise.

  • previously auterei for list return type and ran.

0

Usually only makes the method call inside himself when working with Graphs.

As you are using a list, just move on to the next element.

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

    free(rem)
}

This section 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 snippet removes an item from the list

  • It’s still on an infinite loop.

  • you are using a circular list? your problem may not be in the deletion, but in some part of the implementation. There may be some wrong memory address that causes the list to loop.

  • I created a new code, it must have been a memory problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.