使用C ++以递归方式打印LinkedList [英] Print LinkedList Recursively using C++

查看:240
本文介绍了使用C ++以递归方式打印LinkedList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试创建一个函数来递归地打印我的链接列表,但是我遇到了麻烦,因为递归是很困难的。这是我写的函数,显然需要一个参数,但我不知道如何传递它。可能输出是错误的。



我使用typedef:

  typedef struct node * nodePtr; 

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



声明与void List :: PrintListRecursively不兼容,所以我不知道我传递参数的方式只是一个稍微不同。



预先感谢您

  PrintListRecursively(nodePtr curr){

if(curr == NULL)
{
cout< \\\
;
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 ;& \\\
;
return;
}
cout<< curr-> data<< endl;
PrintListRecursively(curr-> next);
}

然后使用头部指针调用:

  list.PrintListRecursively(list.GetHead()); 

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

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

这会调用带有指针参数的版本。


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

这篇关于使用C ++以递归方式打印LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆