I'm trying to create a function that would print out my link list recursively, but I'm having trouble doing that, because recursion is just hard.
This is the function I wrote, obviously takes a parameter, but I don't know how to pass it. And probably the output is wrong.
I used typedef:
typedef struct node* nodePtr;
and thanks to the input from one of the guys, I updated my function to look like this, but now visual studio is giving an error that says:
"Declaration is incompatible with void List::PrintListRecursively", so I wonder that the way I pass the parameter is just a slight different.
thank you in advance
void List::PrintListRecursively(nodePtr curr ){
if (curr==NULL)
{
cout << "\n";
return;
}
cout << curr->data <<endl;
PrintListRecursively(curr->next);
}
I wrote the same function not recursively:
void List::PrintList(){
curr = head;
while(curr != NULL)
{
cout << curr->data <<endl;
curr = curr->next;
}
}
and this one works great. Could somebody help out with the recursion part and help me find out whats wrong. Don't be too mean.
Your recursive version needs an input:
void List::PrintListRecursively(Node* curr)
{
if (curr==NULL)
{
cout << "\n";
return;
}
cout << curr->data <<endl;
PrintListRecursively(curr->next);
}
Which you would then call using the head pointer:
list.PrintListRecursively(list.GetHead());
Or you could create a version that takes no parameters:
void List::PrintListRecursively()
{
PrintListRecursively(GetHead());
}
Which calls the version that takes the pointer parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With