使用C++递归打印LinkedList

Print LinkedList Recursively using C++

本文关键字:LinkedList 打印 递归 C++ 使用      更新时间:2023-10-16

我正试图创建一个函数,以递归方式打印我的链接列表,但我很难做到这一点,因为递归很难。

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

我用的是typedef:

 typedef struct node* nodePtr;

多亏了其中一个人的输入,我更新了我的功能,看起来像这样,但现在visualstudio给出了一个错误,上面写着:

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

提前感谢

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

}

我不是递归地写了同样的函数:

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

这个效果很好。有人能帮我解决递归部分的问题吗?帮我找出问题所在。不要太刻薄。

您的递归版本需要一个输入:

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

然后您可以使用头指针调用:

list.PrintListRecursively(list.GetHead());

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

void List::PrintListRecursively()
{
    PrintListRecursively(GetHead());
}

它调用采用指针参数的版本。