Inserting a Node Into a Sorted Doubly Linked List

  • + 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;
    

    }