LeetCode 两数相加

# 代码

``````

public static class ListNode {
int val;
ListNode next;

ListNode() {
}

ListNode(int val) {
this.val = val;
}

ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
}
public ListNode addTwoNumbers2(ListNode l1, ListNode l2, int remain) {
if (l1 == null && l2 == null) return remain != 0 ? new ListNode(remain, null) : null;
if (l1 != null) {
remain = l1.val + remain;
l1 = l1.next;
}
if (l2 != null) {
remain = l2.val + remain;
l2 = l2.next;
}
return new ListNode(remain % 10, addTwoNumbers2(l1, l2, remain / 10));
}

``````public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int a = 0;
ListNode cur = l1;
while (l1 != null && l2 != null) {
a = l1.val + l2.val + a;
cur.val = a % 10;
a = a / 10;
l1 = l1.next;
l2 = l2.next;
cur.next = l1 != null ? l1 : l2;
if (cur.next == null && a != 0) {
cur.next = new ListNode(a, null);
a = 0;
}
cur = cur.next;
}
while (cur != null && a != 0) {
a = cur.val + a;
cur.val = a % 10;
a = a / 10;
if (cur.next == null && a != 0) {
cur.next = new ListNode(a, null);
a = 0;
}
cur = cur.next;
}