Inserting a Node Into a Sorted Doubly Linked List

Sort by

recency

|

1070 Discussions

|

  • + 0 comments

    Any c++ help?

  • + 0 comments
    *PYTHON Whenever we have to change the head ,its best practice to create a dummy node as head
    
    def sortedInsert(llist, data):
        dummy=DoublyLinkedListNode(float('-inf'))
        dummy.next=llist
        llist.prev=dummy
        y=dummy
        while (dummy):
            previous=dummy
            if(dummy.next and dummy.next.data>=data and dummy.data<=data):
                x=DoublyLinkedListNode(data)
                dummy.next,x.next=x,dummy.next
                x.prev=dummy
                x=x.next.prev
                return y.next
            dummy=dummy.next
                
                
          
        x=DoublyLinkedListNode(data)
        x.prev=previous
        previous.next=x
            
                
        return y.next
    
  • + 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

  • + 0 comments

    Answer in javascript function sortedInsert(head, data) { let newNode = new DoublyLinkedListNode(data);

    // Handle empty list or insert at front
    if (!head || data <= head.data) {
        newNode.next = head;
        if (head) {
            head.prev = newNode;
        }
        return newNode;
    }
    
    let current = head;
    while (current.next && current.next.data < data) {
        current = current.next;
    }
    
    // Insert the new node
    newNode.next = current.next;
    if (current.next) {
        current.next.prev = newNode;
    }
    current.next = newNode;
    newNode.prev = current;
    
    return head;
    

    }

  • + 1 comment

    I write the solution and its 100% correct but when i submite i get 5/8 failed but when i use the failed testcase in a custom testcase it just worked , so i think its a BUG