I've made a function to insert a node to a linked list while preserving the list. However, after inserting 2 elements, if the next element is higher than all the others, the program seems to loop infinitely. My conditions show allow the program to break the loop if something happens but it doesn't;
Here's the function. Note that head is a pointer to the first element in the list and is NULL if the list is empty:
//defines the node structure
typedef struct node{
int n;
struct node* next;
}node;
bool insert_node(int value)
{
int t=0;
//If list is empty
if (head==NULL){
node* first = malloc(sizeof(node));
//error checking
if (first==NULL)
return false;
head = first;
first->n=value;
first->next=NULL;
t=1;
}
else{
node* body=malloc(sizeof(node));
if (body==NULL){
t=9;
return false;
}
body->n=value;
node* ptr=head;
node*pre=head;
//putting new node into list
while(t==0){
//error checking
if (ptr==NULL)
break;
//insertion
else if (value<=ptr->n||ptr->next==NULL){
body->next=ptr;
pre->next=body;
t=1;
}
//next node
else if(value>ptr->n){
pre=ptr;
ptr=ptr->next;
}
//If all goes wrong
else
t=9; //breaks loop
}
}
if (t==1)
return true;
return false;
}
You need to handle the case where the entry that you are adding needs to be at the head of the list. Right now you only add to the head when the list is empty. That is handled by changing the if as follows:
if (head==NULL || value < head->n){
node* first = malloc(sizeof(node));
//error checking
if (first==NULL)
return false;
first->next=head;
first->n=value;
head = first;
t=1;
}
Now that the addition to the beginning of the list is taken care of, the else needs a change to get pre and ptr initialized correctly and the insertion condition needs to be changed as follows:
node* ptr=head->next;
node* pre=head;
//putting new node into list
while(t==0){
//insertion
if (ptr==NULL || value<=ptr->n){
body->next=ptr;
pre->next=body;
t=1;
}
//next node
else if(value>ptr->n){
pre=ptr;
ptr=ptr->next;
}
//If all goes wrong
else
t=9; //breaks loop
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments