Question

I wanna to write a function in C to reverse Linked list by recursion, however I see many ways as iterative way (which done with me) .. But in recursive way the function always return 0

Revers Linked List Code

node * r_reverseItem(node * head) {    
    if (head == NULL) //only one elem
        return NULL;

    node * currentNode = head;

    if(currentNode->next == NULL) { 
        //set HEAD to current TAIL since we are reversing list
        head = currentNode; 
        return head; //since this is the base case
    }

    r_reverseItem(currentNode->next);
    currentNode->next->next = currentNode;
    currentNode->next = NULL; //set "old" next pointer to NULL
}

So, what is the problem here in this code please? however, any useful examples or sites are also desirable.

EDIT

Just simply I know where is my fault. I forgot to add a return statement which (killer mistake). So the correct function as below:

   node * r_reverseItem(node * head) {    
    if (head == NULL) //only one elem
        return NULL;

    node * currentNode = head;

    if(currentNode->next == NULL) { 
        //set HEAD to current TAIL since we are reversing list
        head = currentNode; 
        return head; //since this is the base case
    }

       node * newNode =r_reverseItem(currentNode->next);
           currentNode->next->next = currentNode;
           currentNode->next = NULL; //set "old" next pointer to NULL
           return newNode;
}
Was it helpful?

Solution

Original solution implemented in Java , i only translated it to C with your variable names

node* r_reverseItem(node * head)
{
    if( !head )   // empty list
        return NULL;

    if( !(head->next) ) //last element becomes the head of the reversed list
        return head;

    node *currentNode = head->next; //preserve next element
    head->next = NULL;

        node* newHead = r_reverseItem(currentNode);

    currentNode->next = head; 
    return newHead; //once you have head you don't change it 
}

OTHER TIPS

Check this web site , basically it explain three way of reverse a link list with example after you read them you will be able to made it recursively as you want

http://www.codeproject.com/Articles/27742/How-To-Reverse-a-Linked-List-Different-Ways

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top