/**
* 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 res = new ListNode(0);
ListNode head = res;
ListNode cursor1 = l1, cursor2 = l2;
int carry = 0;
while (cursor1 != null || cursor2 != null)
{
int c1 = 0, c2 = 0;
if (cursor1 != null)
c1 = cursor1.val;
if (cursor2 != null)
c2 = cursor2.val;
int sum = c1 + c2 + carry;
ListNode current = new ListNode(sum % 10);
res.next = current;
res = current;
carry = sum / 10;
if (cursor1 != null)
cursor1 = cursor1.next;
if (cursor2 != null)
cursor2 = cursor2.next;
}
if (carry > 0)
{
ListNode last = new ListNode(carry);
res.next = last;
}
return head.next;
}
}