public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = newStack(l1), s2 = newStack(l2);
ListNode h = null;
int carry = 0;
while(!s1.isEmpty() && !s2.isEmpty()) {
int t = s1.pop() + s2.pop() + carry;
h = concat(h, t % 10);
carry = t >= 10 ? 1 : 0;
}
Stack<Integer> s = s1.isEmpty() ? s2 : s1;
while(!s.isEmpty()) {
int t = carry + s.pop();
h = concat(h, t % 10);
carry = t >= 10 ? 1 : 0;
}
if (carry != 0) h = concat(h, carry);
return h;
}
private Stack newStack(ListNode l) {
Stack s = new Stack();
while (l != null) {
s.push(l.val);
l = l.next;
}
return s;
}
private ListNode concat(ListNode h, Integer v) {
ListNode t = new ListNode(v);
t.next = h;
return t;
}