Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = 0;
if (l1 == null && l2 != null) {
sum = l2.val + carry;
l2 = l2.next;
} else if (l1 != null && l2 == null) {
sum = l1.val + carry;
l1 = l1.next;
} else {
sum = l1.val + l2.val + carry;
l1 = l1.next;
l2 = l2.next;
}
if (sum >= 10) {
carry = 1;
sum = sum - 10;
} else {
carry = 0;
sum = sum;
}
ListNode res = new ListNode(sum);
curr.next = res;
curr = curr.next;
}
if (carry == 1) {
ListNode car = new ListNode(carry);
curr.next = car;
curr = curr.next;
}
return dummyHead.next;
}
}
Time Complexity : O(max[l1, l2])
Space Complexity : O(max[l1, l2])