Akash Rupela
Akash Rupela

Reputation: 159

C++ : Help needed to debug generic linked list

Below is my attempt at generic representation of a linked list, where i pass an example with integers. I know that the problem is with how i am assigning next (through the add_to_list function), but after staring at screen for 2 hours i still have no clue what is wrong. Could someone guide me through it?

#include<iostream>
using namespace std;

/** Class Definition here */

template<typename  T>
class Linklist
{
    struct node
    {
        node(T value,node* next=NULL):value(value),next(next) {}
        node* next;
        T value;
    };
    node* head;
    node* curr;

public:
    Linklist(node* n=0):head(n) {}
    ~Linklist();
    void add_to_list(T value, bool x=1);
    void print();

};

/** Class destructor */
template<typename T>
Linklist<T>::~Linklist()
{
    node *ptr ;
    while(head!=NULL)
    {
        ptr=head;
        head=head->next;
        delete ptr;
    }
}


template <typename T >
void Linklist<T>::add_to_list(T x, bool z)
// bool basically means if to add the element to beginning or end of list, 1 for end.
{
    node* k=new node(x);
    if(head==NULL)
    {
        k->value=x;
        k->next=NULL;
        head=curr=k;
    }
    else
    {
        k->value=x;
        k->next=NULL;
        if (z==1)
        {
            curr->next=k;
            curr=k;
        }
        else
        {
            k->next=head;
            head=k;
        }
    }
    delete(k);

}

template<typename T>
void Linklist<T>::print()
{
    node* ptr= new node(1);
    ptr=head;
    if (ptr==NULL)
    {
        return ;
    }
    else
    {
        cout<<"reached here \n " <<"pointer is"<<ptr->value<<"\n next is"<<ptr->next;
        while(ptr!=NULL)
        {
            cout<<ptr->value<<"-->";
            ptr=ptr->next;
        }
    }
}


int main()
{
    Linklist<int> *intlist=new Linklist<int>();
    intlist->add_to_list(20,0);
    intlist->add_to_list(344,1);
    intlist->print();
    return 0;
}

Upvotes: 0

Views: 233

Answers (1)

asafrob
asafrob

Reputation: 1858

You delete(k); after you add it to the list so the system can use the memory for new objects. You should not delete it since you are still using that memory

When you don't delete it the output is:

reached here
pointer is20
next is0020882020-->344-->

not related to the bug, but you should avoid new when you can, such as your main code:

Linklist<int> intlist;
intlist.add_to_list(20,0);
intlist.add_to_list(344,1);
intlist.print();

Upvotes: 5

Related Questions