Given two integers in a linked list format, we want to add them and return the result in a linked list format.
Example:
4 8 7 2
3 9 3
Ans:
7 7 1 3
Explanation:
It is a normal addition of number but from left to right.
Solution:
We will iterate each corresponding digits in both linked lists and we add them together.
The key point in solving this problem is knowing that we should use a while loop as we don't know when the loop ends to use a for loop.
The condition of the while loop should as long as there is item in Linked List 1 OR Linked List 2 OR our carryover is greater than 0. As long as these three conditions met we will create a new node and keep adding it to our result linked list.
static Node addIntegers(Node head1, Node head2) {
int carry = 0, h1=0,h2=0, sum;
Node head = null;
Node tail = null;
while(head1 != null || head2 != null || carry >0) {
if(head1!=null)
h1 = head1.val;
else
h1 = 0;
if(head2!=null)
h2 = head2.val;
else
h2 =0;
sum = (carry + h1 + h2) % 10;
carry = (carry + h1 + h2) / 10;
Node n = new Node(sum);
if(head == null) {
head = n;
tail = n;
}
else {
tail.next = n;
}
tail = n;
if(head1!=null)
head1 = head1.next;
if(head2!=null)
head2 = head2.next;
}
return head;
}