Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    Java 15. In java 7 and 8, you may encounter static problem so code in java 15

    DoublyLinkedListNode n = new DoublyLinkedListNode(data);

        if (llist == null) {
            return n;
        }
    
        // Case when the new node needs to be inserted at the beginning
        if (data < llist.data) {
            n.next = llist;
            llist.prev = n;
            return n;
        }
    
        DoublyLinkedListNode current = llist;
        while (current.next != null && current.next.data < data) {
            current = current.next;
        }
    
        // Insert the new node
        n.next = current.next;
        if (current.next != null) {
            current.next.prev = n;
        }
        current.next = n;
        n.prev = current;
    
        return llist;