Reverse a Linked List -

Hey, I was playing with code and found something

    node* reverse(node*head){
        if(head->next == NULL|| head == NULL){
            return head;
        }
        node* smallHead = reverse(head->next);
        node *c  = head;
        c->next->next = c;
        c->next = NULL;
        return smallHead;

    }
how/Why above is different from
node* reverse(node*head){
    if(head->next == NULL|| head == NULL){
        return head;
    }
    node* smallHead = head->next;
    reverse(smallHead);
    node *c  = head;
    c->next->next = c;
    c->next = NULL;
    return smallHead;

}

You can test it here https://ide.codingblocks.com/s/61422

Why they are different?
@sanjeetboora
@Khushboo
They both show different output.

Hi Lakshay, the first code would work fine because you’re storing the answer of recursive call and returning it every time.
The second code will not work properly because you’re not storing the answer returned by recursive call anywhere. You’re just returning smallHead and smallHead contains a pointer to head->next.

Dry run your code for a small input like 1->2->3->4->null for a better understanding.

1 Like