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;
}
if (head == NULL) //only one elem. If head is NULL, then you have zero elements.returnis not reached. Can you spot that place?