Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    Java 15

     public static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode llist, int data) {
            DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);
    
            if (llist == null) {
                return newNode; 
            }
    
            if (data <= llist.data) {
                newNode.next = llist;
                llist.prev = newNode;
                return newNode;
            }
    
            DoublyLinkedListNode current = llist;
    
            while (current.next != null && current.next.data < data) {
                current = current.next;
            }
    
            newNode.next = current.next;
            if (current.next != null) {
                current.next.prev = newNode;
            }
            current.next = newNode;
            newNode.prev = current;
    
            return llist;
        }