【问题标题】:Print LinkedList Recursively using C++使用 C++ 递归打印链表
【发布时间】:2025-12-07 01:50:01
【问题描述】:

我正在尝试创建一个函数,可以递归地打印出我的链接列表,但我在这样做时遇到了麻烦,因为递归很难。

这是我写的函数,明明是带参数的,但是不知道怎么传。并且可能输出是错误的。

我使用了typedef:

 typedef struct node* nodePtr;

感谢其中一个人的输入,我将函数更新为如下所示,但现在 Visual Studio 给出了一个错误消息:

"Declaration is incompatible with 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;
    }
}

而且这个效果很好。有人可以帮助解决递归部分并帮助我找出问题所在。不要太刻薄。

【问题讨论】:

  • 递归示例有什么问题?为什么输出错误?你能发布一个小的工作示例吗?
  • 递归并不难。在函数定义中声明参数。 cplusplus.com/doc/tutorial/functions2
  • 我编辑了问题

标签: c++ recursion linked-list


【解决方案1】:

您的递归版本需要输入:

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());
}

调用带指针参数的版本。

【讨论】: