使用 C++ 递归打印 LinkedList
我正在尝试创建一个函数来递归地打印出我的链接列表,但我在这样做时遇到了麻烦,因为递归太难了.
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.
我使用了 typedef:
I used typedef:
typedef struct node* nodePtr;
多亏了其中一个人的输入,我更新了我的函数,看起来像这样,但现在 Visual Studio 给出了一个错误:
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:
声明与 void List::PrintListRecursively 不兼容",所以我想知道我传递参数的方式只是略有不同.
"Declaration is incompatible with void List::PrintListRecursively", so I wonder that the way I pass the parameter is just a slight different.
先谢谢你
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.
推荐答案
您的递归版本需要输入:
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.
相关文章