Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
递归解法
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return add(l1, l2, 0);
}
private ListNode add(ListNode a, ListNode b, int carry) {
if (a == null && b == null) {
if (carry == 0) {
return null;
}
return new ListNode(carry);
}
int value = carry;
if (a != null) {
value += a.val;
}
if (b != null) {
value += b.val;
}
ListNode re = new ListNode(value % 10);
re.next = add(a == null ? null : a.next, b == null ? null : b.next, value/10);
return re;
}
非递归解法
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
int carry = 0;
while (l1 != null || l2 != null) {
int value = (l1 != null ? l1.value : 0) + (l2 != null ? l2.value : 0) + carry;
carry = value / 10;
cur.next = new ListNode(value % 10);
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
cur = cur.next;
}
if (carry > 0) {
cur.next = new ListNode(carry);
}
return dummy.next;
}