views:

224

answers:

1

hey , 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  A: 

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;
}
NomeN
no at all 'cause I should use the recursion in my algorithme ... yes,the both algorithmes are true ..what I need is what should I write in the main function to apply my class ...
epsilon_G
@epsilon_G it is what should go in your main.
NomeN