Amal Majeed Amal Majeed - 3 months ago 14
C++ Question

Why can't I insert nodes after head into a C++ linked list?

Could someone please help me identify the problem with the code below.

#include <iostream>

using namespace std;

struct node
{
int a,b;
struct node* next=NULL;
};

node* head=NULL;

void insert(int a,int b)
{
if(head==NULL)
{
head=new node;
head->a=a;
head->b=b;
return;
}
node* cur=head;
while(cur!=NULL)
{
cur=cur->next;
}
cur=new node;
cur->a=a;
cur->b=b;
return;
}

void display()
{
node* cur=head;
while(cur!=NULL)
{
cout<<cur->a<<"\t"<<cur->b<<"\n";
cur=cur->next;
}

}

int main()
{
int i;
for(i=0;i<3;++i)
{
insert(i,i+1);
}
display();
//cout<<h->next->a;
return 0;
}


This is the output that I get:

0 1


It seems that I can only display the head node and none after gets inserted. If I try to access the next node after head, I get a segmentation fault. Why is that?

Answer

Your search code is:

node* cur=head;
while(cur!=NULL)
{
    cur=cur->next;
}
cur=new node;

At the end of the loop, you've found the right place to add the new node, but you overwrite that with cur = new node; — so you need to use something more like:

node *new_node = new node;
new_node->a = a;
new_node->b = b;
new_node->next = nullptr;
cur->next = new_node;

Or, equivalently:

cur->next = new node;
cur->next->a = a;
cur->next->b = b;
cur->next->next = nullptr;

Even better, you'd create a constructor for the struct node class, such as:

node(int a_init = 0, int b_init = 0) : a(a_init), b(b_init), next(nullptr) { }

and then:

cur->next = new node(a, b);

would do the whole initialization job.

Comments