I do not understand what you mean by " revert " a list Do you mean to order it in an inverse way?.
Be that as it may, your recursion is useless. The function reverse
returns a pointer to Node
, but you do not use that return at all. You only return a Node
when you have reached the last node, in the rest of cases you do not return anything and the function ends ... what is a undefined behavior .
Node * reverse(Node * list){
if(list->sig==0){
// Devuelves el nodo que no apunta a un siguiente
// es decir: el ultimo nodo.
return list;
}
// Llamas recursivamente a la funcion Y NO RECOGES EL VALOR DE RETORNO
reverse(list->sig);
(list->sig)->sig=list;
list->sig=0;
} // FINALIZAS LA FUNCION SIN DEVOLVER NINGUN VALOR!!!!
Your nodes are structured like this:
And what is happening?
- We call
reverse
with NodoA .
-
NodeA
->sig
is not 0
(is NodeB ), the if
is not met.
- You call
reverse
with NodeA ->sig
which is NodeB .
-
NodeB
->sig
is not 0
(it's NodeC ), the if
is not met.
- You call
reverse
with NodeB ->sig
which is NodeC .
-
NodeC
->sig
is 0
the if
is met.
- Return NodeC .
- The value returned by the previous call is discarded (not picked up).
- It is pointed to the next of NodeB (which is
NULL
) to NodeB .
- Point to the following from NodeB (which is NodeC ) to
NULL
.
- Ends the function without returning anything.
- The value returned by the previous call is discarded (not picked up).
- Point to the next following of NodeA (which is
NULL
) to NodeA .
- Point to the following from NodeA (which is NodeB ) to
NULL
.
- Ends the function without returning anything.
- That nothing that you have returned, which could be anything 1 , is stored in
l
.
- You call the
print
function with whatever l
contains.
After calling reverse
your nodes will be structured like this:
Suggestions.
You should correct the error in reverse
by returning a value in all execution paths.
You should not mix concepts, a Node and a List are not the same, create a List class that contains Nodes, do not treat the Nodes as if they were a 2 list. The functions that you already have created ( inert
, print
and reverse
) would belong to the class List and the nodes would be private data of the same.
.
1 It could be a valid pointer, an invalid pointer, the first parameter passed to the function, the keys to enter the Pentagon or a random memory address.
2 It's as inadequate as saying that a Beja is a Car, although Cars have Bugs, Bugs will never be Cars.