Insert a node into a sorted doubly linked list Solution

Insert a node into a sorted doubly linked list Solution


Problem Statement

You’re given the pointer to the head node of a sorted doubly linked list and an integer to insert into the list. Create a node and insert it into the appropriate position in the list. The head node might be NULL to indicate that the list is empty.

Source Code:

 Node* SortedInsert(Node *head,int data)  
 {  
   // Complete this function  
   // Do not write the main method.   
   Node *temp = new Node;  
   temp->data = data;  
   temp->next = NULL;  
   temp->prev = NULL;  
   if(head == NULL){  
     head = temp;  
   }else{  
     Node *temp1 = temp;  
     temp->next = head;  
     head = temp;  
     while(temp!= NULL){  
       temp1 = temp;  
       temp = temp->next;  
       if(temp!=NULL){  
         if(temp1->data>temp->data){  
           int tdata;  
           tdata = temp1->data;  
           temp1->data = temp->data;  
           temp->data = tdata;  
         }  
       }  
     }  
   }  
   return head;  
 }  

7 comments :