使用C++递归打印LinkedList

Wil*_*ill 2 c++ recursion linked-list

我正在尝试创建一个递归打印出我的链接列表的函数,但是我很难做到这一点,因为递归很难.

这是我写的函数,显然需要一个参数,但我不知道如何传递它.可能输出是错误的.

我用过typedef:

 typedef struct node* nodePtr;
Run Code Online (Sandbox Code Playgroud)

并且感谢其中一个人的输入,我更新了我的功能看起来像这样,但现在visual studio正在给出一个错误:

"声明与void List :: PrintListRecursively不兼容",所以我想知道我传递参数的方式只是略有不同.

先感谢您

void List::PrintListRecursively(nodePtr curr ){

    if (curr==NULL)
    {
        cout << "\n";
        return;
    }
    cout << curr->data <<endl;
    PrintListRecursively(curr->next);


}
Run Code Online (Sandbox Code Playgroud)

我没有递归地编写相同的函数:

void List::PrintList(){
    curr = head;
    while(curr != NULL)
    {
        cout << curr->data <<endl;
        curr = curr->next;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个很棒.有人可以帮助解决递归问题并帮助我找出错误的原因.不要太吝啬.

Zac*_*and 6

您的递归版本需要输入:

void List::PrintListRecursively(Node* curr)
{
    if (curr==NULL)
    {
        cout << "\n";
        return;
    }
    cout << curr->data <<endl;
    PrintListRecursively(curr->next);
}
Run Code Online (Sandbox Code Playgroud)

然后使用头指针调用它:

list.PrintListRecursively(list.GetHead());
Run Code Online (Sandbox Code Playgroud)

或者您可以创建一个不带参数的版本:

void List::PrintListRecursively()
{
    PrintListRecursively(GetHead());
}
Run Code Online (Sandbox Code Playgroud)

哪个调用带有指针参数的版本.