4

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.

2
  • What is the problem with the recursive example? Why is the output wrong? Could you post a small working example? Commented Nov 26, 2013 at 20:03
  • Recursion isn't hard. Declare the parameter in the function definition. cplusplus.com/doc/tutorial/functions2 Commented Nov 26, 2013 at 20:04

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.