Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    Easy to understans Solution in C++

    DoublyLinkedListNode *t = new DoublyLinkedListNode(data); 
        
        if(llist==nullptr ){
            return t; 
        }
        
        else if( llist->next==nullptr && llist->data<data){
            llist->next=t;
            t->prev=llist;
        }
        else if(llist->data >data){
            DoublyLinkedListNode *te = new DoublyLinkedListNode(llist->data);
            DoublyLinkedListNode* Next=llist->next;
            llist->data=data;
            te->next=llist->next;
            Next->prev=te;
            te->prev=llist;
            llist->next=te;
            return llist;
        }
        DoublyLinkedListNode* temp =llist;
        while(temp->next!=nullptr){
            temp=temp->next;
        }
        if(temp->data<data){
            temp->next=t;
            return llist;
        }
        temp=llist;
        while(temp->data < data){
            temp = temp->next;
        }
        DoublyLinkedListNode* temp2 =temp->prev;
        cout<<temp2->data;
        temp2->next=t;
        t->prev=temp2;    
        t->next=temp;
        temp->prev=t;
        return llist;