I am trying to reverse a link list using recursion. I have written a function “reverse(node* ptr) for this
I am getting output as 40 40 20 while i expect output to be 40 , 20 , 10.
below is the code posted.
class list {
//some code;
void reverse()
{
node* temp = new node;
temp =first;
reverse(temp);
temp =NULL;
delete temp;
}
void reverse(node* ptr) {
if(ptr->next != NULL)
{
ptr =ptr->next;
reverse(ptr);
}
cout << ptr->data << endl;
}
// some code;
};
int main()
{
list ll;
ll.insert(18);
ll.insert(20);
ll.insert(40);
ll.display();
ll.reverse();
return 0;
}
please suggest what I am doing wrong here.
Thanks
You should get rid of the line
ptr =ptr->next;.The main objective is to print all the nodes that come after the current node before printing value of the current node. So simply a call to
reverse(ptr->next)followed by acout<<ptr->data<<endlshould suffice, since the first call takes care of all nodes afterptr. There is no need to advance the pointer as we want to print the current node at the end.