0

I have a simple algorithm to add a node in a sorted LinkedList in Java. The issue is with insertBefore method. When the call returns to the calling method, the reference (node) is not updated with pointing to the new node. Java is call by reference and should update the underlying object value, according to my understanding. Any help appreciated.

Below is the code:

public MyListNode<Integer> findAndInsert(MyListNode<Integer> node, int nbr)
{

    MyListNode<Integer> head = node;
    MyListNode<Integer> tail = null;

    boolean inserted = false;

    //Sample Input: 2, 3, 5, 7, 9;  1
    //Sample Output: 1, 2, 3, 5, 7, 9

    if(nbr <= node.data)
    {
        insertBefore(node, nbr);
        inserted = true;
    }
    else
    {
        while(node != null && node.next != null)
        {
            if( nbr <= node.next.data )
            {

                insertAfter(node, nbr);
                inserted = true;
                break;
            }

            if(node.next.next == null)
            {
                tail = node.next;
            }

            node = node.next;
        }
    }

    if(!inserted)
    {
        insertAfter(tail, nbr);
    }
    return head;
}

public void insertAfter(MyListNode<Integer> node, int i)
{
    MyListNode<Integer> n = new MyListNode<Integer>(new Integer(i));

    n.next = node.next;
    node.next = n;
}

public void insertBefore(MyListNode<Integer> head, int i)
{
    MyListNode<Integer> newNode = new MyListNode<Integer>(new Integer(i));


    newNode.next = head;
    head = newNode;
}
jine
  • 99
  • 2
  • 7

0 Answers0