Know if 2 lists are equal recursive method

0

I am trying to implement a recursive function that returns True if 2 lists are equal.

list is a pointer to a structure of this style:

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

typedef nodo *lista;

The code I did was this:

bool iguales(lista l1, lista l2) {

   if ((l1 != NULL) && (l2 != NULL) && (l1->elem == l2->elem))
      return (iguales(l1->sig, l2->sig));
   else if ((l1 == NULL) && (l2 == NULL)
      return false;

}

But it's wrong because when checking both lists and therefore they are NULL I put false back.

I just do not know how to do it.

I need to do it recursively, yes or yes.

edit: What I find hard to understand is the issue of returning the function, if it was a procedure I would not have problems to do it, I think.

    
asked by Edu 06.04.2018 в 19:48
source

1 answer

1

I've managed to make it work like this:

bool iguales(lista l, lista p) {

   if ((l != NULL) && (p != NULL)) {

      if (l->elem != p->elem)
         return false;
      else
         return (iguales(l->sig, p->sig));

   }

   if (l == p) // si son ambas NULL
      return true;
   else
      return false;

}

but I do not think that it is with the best possible efficiency any more efficient solution? even if it's a simple change of line ....

    
answered by 06.04.2018 в 21:45