You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode header = null;
int forward = 0;
ListNode temp = null;
while (l1 != null && l2 != null) {
int digitCount = l1.val + l2.val + forward;
forward = digitCount / 10;
if (header == null) {
header = temp = new ListNode(digitCount % 10);
} else {
temp.next = new ListNode(digitCount % 10);
temp = temp.next;
}
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
temp.next = l1;
temp = temp.next;
int count = (l1.val + forward);
l1.val = count % 10;
forward = count / 10;
l1 = l1.next;
}
while (l2 != null) {
temp.next = l2;
temp = temp.next;
int count = (l2.val + forward);
l2.val = count % 10;
forward = count / 10;
l2 = l2.next;
}
if (forward != 0) {
temp.next = new ListNode(forward);
}
return header;
}
}