0
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode p = l1, q =l2;
    int carry = 0;
    ListNode result = new ListNode(0);
    ListNode temp = result;
    
    while (p != null || q != null) {
        int x = p == null ? 0 : p.val;
        int y = q == null ? 0 : q.val;
        int sum = x + y + carry;
        carry = sum/10;
        int node = sum % 10;
        temp.next = new ListNode(node);
        p = (p != null && p.next != null) ? p.next : null;
        q = (q != null && q.next != null) ? q.next : null;
        temp = temp.next;
    }
    
    if(carry != 0)
    {
        temp.next = new ListNode(carry);
    }
    
    return result.next;
}

My question is about variable temp and result. In my mind, temp and result are two different object with same initial value, and result should not modified as temp modified in the while loop. Appreciate for any suggestion

Shawn L
  • 64
  • 1
  • 8

2 Answers2

1

When you created ListNode result = new ListNode(0); a new object is created and the variable result is the reference to the object. The statement ListNode temp = result; leads to assigning object reference of result to temp. Since both the variables are pointing to the same object modifying one modifies the other.

Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35
  • it that mean object variable always pass by reference in java? – Shawn L Jul 11 '20 at 18:33
  • 1
    When we pass the variable in a function, its pass by value as we copy the reference value. You can refer this [link](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) for a good explanation – Deepak Patankar Jul 11 '20 at 18:37
  • @ShawnL no, Java is **never** pass-by-reference – QBrute Jul 11 '20 at 19:27
1

In Java, when you assign a variable of one type to another variable of the same type, as you did with ListNode temp = result;, java automatically makes the temp variable a reference type. This means that there is no copying going on, and the temp variable points to the exact same object, and the exact same memory address, as the result variable. This means that when you do a change to the temp variable, the same change applies to the result object because, in reality, they are the same object.