Some error occured while loading page for you. Please try again.
You are viewing a single comment's thread. Return to all comments →
you do not assign the address to pointer temp
Node* Insert(Node *head,int data)
temp=new Node(); //That's the statement missing
temp->data = data;
temp->next = NULL;
if(head == NULL)
head = temp;
p = head;
while(p->next != NULL)
p = p->next;
p->next = temp;
//in cpp , giving a segmentation fault
why is the above code giving me segmentation fault
When you exit the while loop you have a pointer pointing to nowhere. It didn't matter on the Print exercise, but here it does.
In your else statement, create another Node* pointer variable (*tail, for instance), and make it receive your *p at each iteration.
At the last iteration, it will be pointing to the last Node structure, which will be the tail of the linked list. Then your p->next=temp; will work :-) !