链表递归... [英] Linked list Recursion ...

查看:96
本文介绍了链表递归...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哎, 我想用做递归函数的C ++

hey , I'd like to make a recursive function using C++

我使这个类

class linklist
{
private:
  struct node
  {
    int data;
    node *link;
  }*p;
};

void linklist::print_num(node* p)
{
  if (p != NULL) 
  {
    cout << p->data << " ";
    print_num (p->link);
  }
}

在主程序是我应该写...

in the main program what should I write ...

推荐答案

1:构建列表 - 2:保留第一个节点
3: print_num 第一个节点上

1: Build the list
2: Retain the first node
3: print_num on the first node

我不得不改变很多在code,使其工作。我猜你用来编写Java ...

I had to change a lot in your code to make it work. I'm guessing you used to write Java...

但是,在我主我得到:

node *first = NULL;
for (int i = 10; i > 0; i--) {
    node *temp =  new node;
    temp->data = i;
    temp->link = first; 
    first = temp;
}

linklist::print_num(first);

更新1:

好吧,显然你没有得到你所应该做的这块code,所以我现在张贴了整个事情给你。认为自己很幸运,并试图从中吸取教训。 如果您还有问题,请让你的问题/需求更清晰。

Ok, apparently you didn't get what you should do with this piece of code, so I am now posting the whole thing for you. Consider yourself very lucky, and try to learn from it. If you still have issues please make your question/requirements clearer.

#include <iostream>

using namespace std;

struct node {  
    int data;
    node *link;
};

class linklist {
public:

    static void print_num(node* p) {
    if (p != NULL)    {   
           cout << p->data << " ";
        print_num (p->link);    
       }
    }
};

int main() {
    node *first = NULL;
    for (int i = 10; i > 0; i--) {
        node *temp =  new node;
        temp->data = i;
        temp->link = first; 
        first = temp;
    }

    linklist::print_num(first);

    return 0;
}

更新2:

在你的code被重新格式化,我注意到,你想保持节点结构隐患。 为了能够做到这一点,你需要一个add方法在你的类,它可以添加节点,您可以在没有节点调用打印方法。

After your code was reformatted, I noticed that you wanted to keep the node struct hidden. To be able to do that, you do need an add method in your class which can add the nodes and a print method which you can call without a node.

所以考虑到这一点,我想出了这一点:

So with that in mind I came up with this:

#include <iostream>

using namespace std;

class linklist {
public:
    linklist();

    void print();
    void add(int number);

private:
    struct node {
        int data;
        node *link;
    };
    void print_num(node *p);
    node* start;
};

linklist::linklist() {
    start = NULL;
}

void linklist::print() {
    print_num(start);
}

void linklist::add(int number) {
    node* temp = new node;
    temp->data = number;
    temp->link = start;
    start = temp;
}

void linklist::print_num(node *p) {
    if (p != NULL)    {   
        cout << p->data << " ";
        print_num (p->link);    
    }
}

int main() {
    linklist list;
    for (int i = 10; i > 0; i--) {
        list.add(i);
    }

    list.print();

    return 0;
}

这篇关于链表递归...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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