Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

recursion - Print LinkedList Recursively using C++

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 << "
";
        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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your recursive version needs an input:

void List::PrintListRecursively(Node* curr)
{
    if (curr==NULL)
    {
        cout << "
";
        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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...