Delete element x from a list - Recursion

1

I have to create a function that removes all the elements with numerical data x from a list.

My Code:

struct nodolista {
    int elem;
    nodolista *sig;
};

typedef nodolista *lista;

void remover(int x, lista l) {
   if (l != NULL) {
      remover(x, l->sig);
      if (l->elem == x)
         delete l;
   }
}

But it does not work correctly, because when you delete an element, the one before it does not connect with your next one. I can do this with iterative mode, but not recursively.

    
asked by Edu 07.04.2018 в 00:27
source

1 answer

1

Make the recursive call that returns the next one, in this way you can assign it to the current recursive call if you have not deleted it. That is, when calling the following:

  • If null returns null to assign it to the previous one.
  • If it is the one that you have to eliminate, assign the following one to a temporary one (since you are going to eliminate it), delete it, and make the recursive call with the following one.
  • If you do not have to delete it, assign the following as the next recursive call to this one.

Or said in a more summarized way:

  • If you do not delete the next one - > you assign it
  • If you delete the next one - > assign the following one that you are not going to eliminate (or null if there are no more).

I leave you the recursive function code:

lista remover(int x, lista l) {

    if (l == NULL) {
        return l;       // Devolvemos NULL
    } else {
        if (l->elem == x) {
            lista tmp = l->sig; // Asignamos el siguiente a un temporal.
            delete l;           // Eliminamos el actual.
            return remover(x, tmp);   // Devolvemos lo que devuelva la llamada recursiva con el siguiente
        }
        else {
            l->sig = remover(x, l->sig);  // Asignamos lo que devuelva la llamada recursiva con el siguiente.
            return l;                     // Devolvemos el actual;
        }
    }
}

I hope to have explained myself, but do not hesitate to comment on the answer and try to explain myself better.

How you comment @Xam You can use nullptr instead of null from C ++ 11.

    
answered by 07.04.2018 / 02:10
source