LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) {
if(l1 == null && l2 == null && carry == 0) {
return null;
}
LinkedListNode result = new LinkedListNode(carry,null,null);
int value = carry;
if(l1 != null)
value += l1.data;
if(l2 != null)
value += l2.data;
result.data = value % 10;
//Recursive call
if(l1 != null || l2 != null || value >= 10) {
LinkedListNode more = addLists(l1 == null? null : l1.next,
l2 == null? null : l2.next,
value >= 10? 1 : 0);
result.setNext(more);
}
return result;
}
My doubts with the recursive call of addLists(arg1,arg2,arg3)
are:
- What exactly is stored at
more
after each recursive call? In other words, willmore
stack up the result of each recursive call? - Will the statement (after the recursive call),
result.setNext(more)
, be executed in every recursive call? - How will the final
return
value work?
I understand the concept of recursion and have gone through various other answers. However, the scenario of return
statement along with the recursive call being assigned to more
seem different, and have made it confusing. Would really appreciate a simple explanation of this scenario. Thanks.