Wednesday, 23 September 2015

Hackerrank 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;  
 }  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)