I know there are many questions that are based on segmentation fault core dumped in C++ in here but I am not able to resolve this error. My code is simple to create a link list and print it. I want to know why it is wrong because I am new to this topic and want to learn more and how it works and what errors means.
The code is below:
using namespace std;
struct node
{
int data;
node *next;
};
node *head =NULL;
void addnode(int x)
{
node *temp =new node;
temp->data = x;
temp ->next = NULL;
if(head==NULL)
{
head = temp;
}
else
{
node *p =head;
while(p!=NULL)
{
p=p->next;
}
p->next =temp;
temp =NULL;
}
}
void display(node *head)
{
node *temp=new node;
temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" , ";
temp = temp->next;
}
cout<<endl;
}
int main()
{
cout<<"Hello World";
node work;
addnode(12);
addnode(11);
addnode(1);
addnode(22);
display(head);
return 0;
}
Most probably I am messing with the head pointer and that's why such an error is occurring but I want to know with respect of my code what I am doing wrong in here.
Thank You. Much Appreciated .