1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { l1 = reverse(l1, null); l2 = reverse(l2, null); ListNode l3 = addTwo(l1, l2); return reverse(l3, null); }
private ListNode addTwo(ListNode l1, ListNode l2) { ListNode head = new ListNode(), tail = head; int c = 0; while (l1 != null || l2 != null) { if (l1 != null) c += l1.val; if (l2 != null) c += l2.val; tail.next = new ListNode(c % 10); tail = tail.next; c /= 10; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; } if (c > 0) { tail.next = new ListNode(c); } return head.next; }
private ListNode reverse(ListNode cur, ListNode pre) { if (cur == null) return pre; ListNode head = reverse(cur.next, cur); cur.next = pre; return head; } }
|