reverse link list using recursion
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
Before even talking about the linked list, there is a major problem with your code:
void reverse()
{
node* temp = new node;
temp =first;
reverse(temp);
temp =NULL;
delete temp;
}
You allocate space for a node
and then change what it is pointing to, to first
. This means the memory you allocated will be leaked. Not only that but you then set it to NULL and then try to free it. You can't free NULL!
I believe you simply meant:
void reverse()
{
reverse(first);
}
Simple. On to the linked list:
if(ptr->next != NULL)
{
ptr =ptr->next;
reverse(ptr);
}
You set ptr
to the next element so when reverse()
returns it will be one element ahead. I believe you meant:
if(ptr->next != NULL)
{
reverse(ptr->next);
}
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 a cout<<ptr->data<<endl
should suffice, since the first call takes care of all nodes after ptr
. There is no need to advance the pointer as we want to print the current node at the end.
精彩评论