I am trying to print a linked list in reverse order using recursion, but I think the logic is not right as the output only gives me the first node of the original list, nothing else.
This is the function
void reverseListRec(node *&head1){
node *temp = head1;
if(temp == NULL || temp -> next == NULL ){
head1 = temp;
return;
}
reverseListRec(head1 -> next);
temp -> next -> next = temp;
temp -> next = NULL;
return;
}
This is the part where I call it.
node *head = NULL;
cin>>head;
reverseListRec(head);
cout<<head<<endl;
I have used operator overloading to input and output the LinkedList which is working fine, but after the recursive call is where the problem starts.
Any help would be much appreciated.
Thank You.
The main issue is that you only change head1
when reaching the base case of recursion, but since in the recursive case you don't pass head1
itself as argument to the recursive call, there is no way that head1
is going to change. What is changed is head1 -> next
. So you actually never change the original head of the list.
Here is a correction of the part that deals with the recursive case:
// Update `head1` here too
head1 = head1 -> next;
// And have the recursion update head1 itself
reverseListRec(head1);
temp -> next -> next = temp;
temp -> next = NULL;