Inserting a Node Into a Sorted Doubly Linked List

  • + 0 comments

    Java

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