I am trying to enter a new node in a sorted linked list. I do not know what is wrong in this code.
Node* SortedInsert(Node *head,int data)
{
struct Node *temp=head,*p=NULL;
struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=NULL;
newNode->prev=NULL;
if(!head){
return newNode;
}
while((data>=(temp->data)) && temp!=NULL){
p=temp;
temp=temp->next;
}
if(temp==NULL){
p->next=newNode;
newNode->prev=p;
return head;
}
if(p==NULL){
head->prev=newNode;
newNode->next=head;
return newNode;
}
p->next=newNode;
newNode->prev=p;
newNode->next=temp;
temp->prev=newNode;
return head;
}
The line
should read
You need to test
temp
is not NULL first otherwise you might do an invalid read which can cause an access violation.