Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example
Input: First List: 5->6->3 // represents number 563 Second List: 8->4->2 // represents number 842 Output Resultant list: 1->4->0->5 // represents number 1405
Following are the steps.
1) Calculate sizes of given two linked lists.
2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate sum of rightmost nodes and forward carry to left side.
3) If size is not same, then follow below steps:
….a) Calculate difference of sizes of two linked lists. Let the difference be diff
….b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate sum of smaller list and right sub-list (of same size) of larger list. Also, store the carry of this sum.
….c) Calculate sum of the carry (calculated in previous step) with the remaining left sub-list of larger list. Nodes of this sum are added at the beginning of sum list obtained previous step.
private int carry = 0;
public ListNode addReversedLinkedList(ListNode a, ListNode b) {
if(a==null) {
return b;
} else if(b==null) {
return a;
}
int m = this.getListSize(a);
int n = this.getListSize(b);
ListNode result;
if(m==n) {
result = this.addListWithSameSize(a, b);
} else {
int diff = Math.abs(m-n);
ListNode list1 = m>n?a:b; // make sure the first list is larger
ListNode list2 = m>n?b:a;
ListNode cur = list1;
while(diff-->0) cur = cur.next;
result = this.addListWithSameSize(cur, list2);
result = this.addRemainingList(list1, cur, result);
}
if(this.carry>0) {
ListNode newRes = new ListNode(0);
newRes.val = this.carry;
newRes.next = result;
return newRes;
}
return result;
}
private int getListSize(ListNode n) {
int size = 0;
while(n!= null) {
n = n.next;
size++;
}
return size;
}
private ListNode addListWithSameSize(ListNode a, ListNode b) {
if(a==null || b==null) return null;
ListNode result = new ListNode(0);
result.next = addListWithSameSize(a.next, b.next);
int sum = a.val+b.val+this.carry;
this.carry = sum/10;
result.val = sum%10;
return result;
}
private ListNode addRemainingList(ListNode list1, ListNode cur, ListNode result) {
if(list1==cur) return result;
ListNode next = addRemainingList(list1.next, cur, result);
int sum = list1.val + this.carry;
this.carry = sum/10;
ListNode ret = new ListNode(0);
ret.val = sum%10;
ret.next = next;
return ret;
}
Reference: