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