Search code examples
data-structureslinked-listcomputer-science

Why this function is not able to hold ref to linkedList element?


My linkedList node is defined as following,

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

and in my main function, I am trying to make a linkedlist from array like below,

public static void main(String[] args) {
        int[] first={9,9,9,9};
        ListNode firstNode=null;
        ListNode firstNodeRef= firstNode;
      
        for (int  i =0;i<first.length;i++){
            firstNode= new ListNode();
            firstNode.val=first[i];
            firstNode= firstNode.next;
        }
    }

Why firstNodeRef is null. Java being ref by value. and when comes to objects the value is actually the ref of object. so, shouldn't this work?


Solution

  • Because it's a reference to the value which stays null and not a reference to the variable.

    I wrote some logic with comments to help explain the point

            int[] first = {9, 9, 9, 9};
            // keep head as a reference to your first node
            ListNode head = new ListNode(first[0], null);
            // curr (short for current) will initially be a reference to head's node (not the head variable)
            ListNode curr = head;
          
            for (int i = 1; i < first.length; i++) {
                // create a new list node that will be referenced by curr.next
                curr.next = new ListNode(first[i], null);
                // update curr to reference our recently created node above
                curr = curr.next;
            }