So in member function print_list() you use a while loop.
void print_list()
{
cout<<"data in list is "<< this->data << endl ;
while(this->next != NULL)
this->next->print_list();
}
But the think is because you use a loop here, each node would call the function indefinitely, because the next variable if NULL, will never be assigned anything else, so you'll keep getting the second element printed.
So your function should look like that:
void print_list() {
cout<<"data in list is "<< this->data << endl;
if (this->next != NULL)
this->next->print_list();
}
Also this:
void add(int data)
{
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
this->next = node_t ;
}
Should be that:
void add(int data)
{
Node* node_t;
Node* last = this;
while(last->next)
last = last->next;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
last->next = node_t ;
}
Or that, if you really like recursion:
void add(int data)
{
Node* last = this;
if (next)
return next->add(data);
Node* node_t;
node_t = new Node();
node_t->data = data;
node_t->next = NULL;
last->next = node_t ;
}
Because if you do not append to the last element, you'd end up rewriting the second element, which also causes a memory leak.
I also hope you have a destructor to free all the memory you've allocated.
Edit: I noticed, that you have a non void return type for methods that don't have a return statement. Make sure you either return something or return type is void.
while(this->next != NULL)should be an if (). Think about what happens in the loop minus the recursion part. When and where do you alterthis->nextto allow the loop to adance?