Search code examples
c++linked-listsingly-linked-listinsertion

Why am I not getting any output, for my code on insertion in linked list?


I am trying to create a singly linked list by inserting nodes at end, and despite having no errors I am unable to print my linked list. Please help me debug my code.

I tried online compiler on codechef and it shows SIGSEGV Runtime error. What is this supposed to mean?

struct node
{
int data;
struct node *next;
};

void insert(struct node *root,int data)
{
struct node *temp=new(struct node);

if(root==NULL)
{
    temp->data=data;
    temp->next=NULL;
}

root->next=temp;
temp->data=data;
temp->next=NULL;

}

void print(struct node *root)
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
    cout<<temp->data;
            temp=temp->next;

}

}

int main()
{
struct node *root=NULL;
insert(root,1);
    insert(root,2);
insert(root,3);
insert(root,4);
print(root);
return 0;
}

Solution

  • Please help me debug my code.

    OK lets try a dry run.

    Imagine your list is empty and you are inserting your first item. So root equals NULL and we call insert.

    1) first thing

    struct node *temp=new(struct node);
    

    You allocate a new node, and set temp equal to it, so far so good.

    2) next thing

    if(root==NULL)
    

    this is true as explained in the preamble, so we enter the if statement

    3) next thing

    temp->data=data;
    temp->next=NULL;
    

    these statements in the if body get executed and initialise the newly allocated object. It's not clear why you only want to do this when root == NULL, I would think you would want to initialise the newly allocated node always. But anyway, so far no errors.

    4) next thing

    root->next=temp;
    

    Now here's the error. Ask yourself, what is the value of root at this point? When we started it was NULL, has anything changed it since? The answer of course is no, so you are dereferencing a NULL pointer. That explains the error.

    You need to be able to look at the code you've written and see it for what it really does. The ability to dry run your code like I did above is a very valuable skill to have.

    Unfortunately your code really is not very close to being correct. So I think the best thing would be to look at some working code and see how it operates and then start again.