简体   繁体   中英

Linked list Issue with printing using recursion

Can anyone point out what might be the issue with this recursion in print list? I get the last element being printed indefinitely.

class Node
{
    public:
    Node* next;
    int data ;
    
     Node()
    {
        this->data = 0;
        this->next = NULL ;
    }
Node add(int data)
{
    Node* node_t;
    node_t = new Node();
    node_t->data = data;
    node_t->next = NULL;
    this->next = node_t ;
            
}
    void print_list()
    {
        cout<<"data in list is "<< this->data << endl ;
        while(this->next != NULL)
            this->next->print_list();
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM