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
node* temp = new node; temp =first;causes memory leak, you allocate a new node, and then you "forget" about it lose its address [note that doesn't address your question, it's a different issue]