Complete the code for the following function: struct node * ordered_list_insert(
ID: 3615126 • Letter: C
Question
Complete the code for the following function:struct node * ordered_list_insert(struct node * list, struct node*new_node);
/* list is a pointer to the first node of a linked list of integersin which the values occur in increasing order; new_node is a nodecontaining a valid integer value. After execution of this function,new_node has been inserted into the list so that it is still anordered linked list. The function returns a pointer to the firstnode of the modified linked list. This is necessary since the valuein new_node could be less than all values in the original list, inwhich case it becomes the new first node */
Explanation / Answer
#include #include struct node { int n; struct node *next; }; struct node * ordered_list_insert(struct node * list, struct node*new_node) { struct node *bptr,*ptr; if(new_node==NULL) return list; if(list ==NULL) return new_node; if(new_node-> n n) { new_node -> next = list; return new_node; } bptr = ptr = list; while(ptr != NULL) { if(ptr->n > new_node->n) break; bptr = ptr; ptr=ptr->next; } bptr->next = new_node; new_node->next = ptr; return list; } int main() { struct node *f=(struct node *)malloc(sizeof(struct node)); struct node *b=(struct node *)malloc(sizeof(struct node)); b->n = 2; struct node *ptr; f->n=1; f->next = (struct node *)malloc(sizeof(struct node)); f->next ->n=3; f->next->next=NULL; ptr = ordered_list_insert(f,b); if(ptr == NULL) printf("one of the node is empty"); else { while(ptr!=NULL) { printf(" Value found:%d",ptr->n); ptr=ptr->next; } } printf(" "); system("pause"); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.