Write a program to insert a node in a sorted linked list.

Showing Answers 1 - 1 of 1 Answers

Sunil Basavaraj.Kamatagi

  • Oct 11th, 2005
 

/*Function to insert a node in singly sorted linked list */

/*pass the header of the list and the element to be inserted */

/*header node i,e head is declared as global */

/*node is a structure which contains int info; and a pointer of node    type i,e next*/

node * insert_in_sort(int ele){

        node *p,*q=NULL;

        node *newnode=(node *) malloc(sizeof(node));

        newnode->info=ele;

        newnode->next=NULL;

        for(p=head;p!=NULL && p->info<ele;p=p->next)

        q=p;

        if(q==NULL) {    /*the node should be inserted first */

              newnode->next=p;

              head=newnode;

       }

      else{

        q->next=newnode;

        newnode->next=p;

    }

 return head;

   

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions