cppcoder
cppcoder

Reputation: 23095

How can I get this recursive linked list reverse work?

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

Answers (2)

Martin Brandl
Martin Brandl

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

kennytm
kennytm

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

Related Questions