This is a LeetCode question, what is asked is to sum up two linked numbers, for example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Question:
The following code use recursive method, every recursive call (the third to last line) will construct a new result
, I am having difficulties to wrap my head around that why would the old result
not be overwritten by the new result
? Is it because these result
s belong to different scopes, for example, scope1.result, scope2.result?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public ListNode op(ListNode l1, ListNode l2, int carry) {
if (l1==null && l2==null) {
return carry==0 ? null: new ListNode(carry);
}
if (l1==null && l2!=null) {
l1 = new ListNode(0);
}
if (l1!=null && l2==null) {
l2 = new ListNode(0);
}
int sum = l1.val + l2.val + carry;
ListNode result = new ListNode(sum % 10);
result.next = op(l1.next, l2.next, sum / 10);
return result;
}