Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments
    def sortedInsert(llist, data):
        # Write your code here
        head = llist
        if data < head.data:
            dat = DoublyLinkedListNode(data)
            head.prev = dat
            dat.next = head
            return dat
        
        while( head ):
            nex = head.next
            
            if not nex :
                dat = DoublyLinkedListNode(data)
                head.next = dat
                break
            if nex and data < nex.data:
                dat = DoublyLinkedListNode(data)
                head.next = dat
                nex.prev = dat
                dat.prev = head
                dat.next = nex
                break
            head = head.next
            
        return llist
        
    

    this worked for me