Inserting a Node Into a Sorted Doubly Linked List

 https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=linked-lists

DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
if(!head) return head;
DoublyLinkedListNode* node=new DoublyLinkedListNode(data);
DoublyLinkedListNode* temp=head;
if(head->data>=node->data){
    head->prev=node;
    node->next=head;
    return node;
}
while(temp!=NULL){
   if(temp->data>=node->data){
       temp->prev->next=node;
       node->prev=temp->prev;
       temp->prev=node;
       node->next=temp;
       break;
   } 
   else if(temp->next==NULL){
       temp->next=node;
       node->prev=temp;
       break;
   }
   temp=temp->next;
}
return head;

}


 

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!