struct Node
{
int data;
Node * next;
Node (int x)
{
data=x;
next=NULL;
}
};
Node * insertInSorted(Node * head, int data)
{
Node* temp = new Node(data);
if (head == NULL){
return temp;
}
if (data < head->data){
temp->next = head
return temp;
}
Node* curr = head;
while (curr->next->data < data && curr->next != NULL){
curr = curr->next;
}
temp->next = curr->next;
curr->next = temp;
return head;
}
Hi, I've recently learned C++ and have been practicing LinkedList, this question is simple all I've to do is insert an element at its correct position while maintaining the sorted order. My question is why am I getting segmentation fault. I noticed that in the while loop if I flip the order from while (curr->next->data < data && curr->next != NULL) to while (curr->next != NULL && curr->next->data < data) segmentation error does not occur. Can someone please help me understand this problem?