Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    Python 3 code

    Inserting a Node Into a Sorted Doubly Linked List

    def sortedInsert(llist, data):
        # q - new node 
        q = DoublyLinkedListNode(data)
        # p - pointer to linked list
        p = llist
        
        # llist is empty
        if(not p):
            return q
            
        # insert at the beginning    
        if(p and data < p.data):
            q.next = p
            p.prev = q
            p = q
            return p
        # while traversing pointer p   
        while(p):
            
            p = p.next
            
            # In-Between 2 nodes
            if(p.data > q.data):
                
                p = p.prev            
                q.next = p.next
                q.prev = p
                if(p.next):
                    p.next.prev = q
                p.next = q
                return llist
                
            else:
                # inserting at the end of the linked list
                if(not p.next):
                    
                    p.next = q
                    q.next = None
                    q.prev = p
                    return llist
                    
                else:
                    continue
       
    

    Do Upvote it if you found it helpful & Do Comment below for any suggestions⛳