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;  
     Node *temp1 = temp;  
     temp->next = head;  
     head = temp;  
     while(temp!= NULL){  
       temp1 = temp;  
       temp = temp->next;  
           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..... :) :) :)


  1. I think your post is very interesting and mostly, I keep looking for like this type of websites where I learn or get new concept. I am happy to visit on your site. Thanks to share it. I was more than happy to find this web site. I need to thank you for your moment due to this unbelievable read!! I definitely savored every bit of it and I have you book-marked to see new things in your web site.

  2. This comment has been removed by the author.

  3. Wow, thank you for the information. It was really interesting and helped me a lot. I wish there were more such good websites, as yours. I always can find everything I need here. The only thing that is missing are reviews on MyAssignmentHelp. Maybe you can include them too?

  4. Sorry to say ,but i think just swapping the data may not be the optimal solution instead you should have use exchange of pointers method to fulfill ur method.

  5. Your blog is awfully appealing. I am contented with your post. I regularly read your blog and its very helpful. If you are looking for the best Algorithm Interview Questions, then visit TutorialCup. Thanks! I enjoyed this blog post.