Reputation: 23095
I tried to write a recursive linked list reverse function and my head is spinning. Can someone please tell me how can I mend the function?
node* recursiveReverse(node* h, node* prev)
{
node* current = h; //Point to current node
node* successor = h->next; //Points to next node
if(successor == NULL)
return prev;
successor->next = recursiveReverse(successor,current);
h->next = NULL;
return successor;
}
Upvotes: 0
Views: 303
Reputation: 58921
You should also try to write the constants first to avoid such problems. For instance: If you write
if ( NULL == successor )
return prev;
and you now forget to write two "=", the compiler throws an error because you can't assign NULL a value.
Upvotes: 1
Reputation: 523224
if(successor = NULL) // <---
return prev;
Should be ==
here. (=
is assignment, ==
is compare for equality).
It is a common problem and most compilers should have issued a warning for this. If you haven't turned on warnings (add the -Wall
flag if you're using gcc or clang), please do so.
Upvotes: 2