You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Output: 7 -> 0 -> 8
Output: 7 -> 0 -> 8
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
ListNode l3 = new ListNode(0);
ListNode head3 = l3;
int ad = 0;
while(head1 != null || head2 != null){
int a = 0;
if(head1 != null){
a = head1.val;
head1 = head1.next;
}
int b = 0;
if(head2 != null){
b = head2.val;
head2 = head2.next;
}
a = a + b + ad;
head3.next = new ListNode(a%10);
head3 = head3.next;
ad = a / 10;
}
if(ad == 1){
head3.next = new ListNode(1);
}
return l3.next;
// return l1;
}
}