Search code examples
c++pointersrecursionlinked-listnodes

Function to reverse a linked list recursively


I was trying to write this function to reverse singly linked list and I'm unable to find what has gone wrong here.

void reverse(node *&c, node *&p){
    if(c = NULL){
        c = p;
        return;
    }
    node *n = c->next;
    c->next = p;
    p = c;
    c = n;
    reverse(c, p);
}

c = current node, p = previous node, n = next node.

I found multiple solutions on the internet having return type 'node*' and some others too but I want to find what's going wrong with my implementation


Solution

  • You have an assignment in your condition if(c = NULL). This is valid c/c++, and will assign NULL to c. The result of the assignment (NULL) is then used as the condition in your if-statement, which will then always evaluate false.

    Replace the assignment with a comparison for equality (==)

    Using side effects in your conditions is bad practice and should be avoided. It can cause hard to find bugs. Even if an assignent is what you want, you should use it before the if statement and then check the variable.
    Other bad side effects may be such things as if (someExpression && (a++ == 5)), where a may or may not be incremented depending on compiler settings.