Trying to diagram what happens in the "doIt" function (it is complete below) I find myself with a specific doubt when making a comparison.
Doubt: After getting the last node and assigning it to the aux pointer. I see the following comparison:
if(aux == lista)
For one: Compare aux -> info and list -> info? Why am I comparing?
On the other, after
aux = obtenerUltimo(lista);
would the diagram look like this?
As an additional comment "getLast" returns the last node in the list. and the structure of the node would be:
struct Nodo
{
int info;
Nodo *sgte;
};
The full function:
int doIt(Nodo *&lista)
{
int elemento;
Nodo *aux; Nodo *aux2;
if(lista)
{
aux = obtenerUltimo(lista);
if(aux == lista) // Duda
{
elemento = lista -> info;
delete lista;
lista = NULL;
return elemento;
}
else
{
aux2 = lista;
while(aux2->sgte != aux)
aux2 = aux2->sgte;
elemento = aux -> info;
delete aux;
aux -> sgte = NULL;
return elemento;
}
}
else
{
cout << "Error: vacia" << endl;
return 0;
}
}
Nope.
What types are
aux
andlista
?:lista
is a reference to pointer toNodo
(Nodo *&lista
).aux
is a pointer toNodo
(Nodo *aux
).For all practical purposes a reference behaves the same as the type it references , so you
aux == lista
are comparing two pointers which is nothing more than comparing the memory address they contain, not the content of what they are pointing to.In other words, the expression
aux == lista
will be true if bothaux
arelista
storing the same memory address.You will know, it is your code. When I read it I don't see much sense in it, at least it should make sense to you who have developed it.
Assuming it
obtenerUltimo
does what you say it does: Yes. But let's see what happens next, first suppose thataux
andlista
point to the sameNodo
:In your code, you save
elemento
to a variable to return later, delete the oneNodo
pointed to bylista
, make it point toNULL
and returnelemento
; After these steps your memory would be similar to this:As you can see, the penultimate
Nodo
remains pointing to theNodo
deletion, I assume that this will be a problem because saidNodo
has not been informed that its following has ceased to exist.When
aux
andlista
do not point to the sameNodo
, you advance another helper pointer (aux2
) to the node beforeaux
, then saveelemento
to a variable to return later, delete the oneNodo
pointed to byaux
, make (after deleting!) its next pointer toNULL
y you returnelemento
. This code will fail at runtime on theaux -> sgte = NULL;
. But assuming that it did not fail, starting from your initial diagram, after these steps your memory would be similar to this:Not only is it wrong for accessing erased memory (
delete aux; aux -> sgte = NULL;
) but also the node it pointsaux2
to has not been informed that its next node has ceased to exist.