开发者

Linked list Recursion ... [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical 开发者_JAVA技巧and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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

I make this class

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: Build the list
2: Retain the first node
3: print_num on the first node

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

But in my main I get:

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

UPDATE 1:

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

UPDATE 2:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜