1 ms, 在所有 Java 提交中击败了100.00% 的用户
41.3 MB, 在所有 Java 提交中击败了76.16% 的用户
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int addNumber = 0;
ListNode l3 = null;
int s = 0;
do {
int a = 0,b=0;
if (l1 != null) {
a = l1.val;
l1 = l1.next;
}
if (l2 != null) {
b = l2.val;
l2 = l2.next;
}
if (0 == s) {
l3 = new ListNode((a + b) % 10);
addNumber = (a + b)>=10 ? 1 : 0;
}else {
add(l3, new ListNode((a + b + + addNumber) % 10));
addNumber = (a + b + addNumber)>=10 ? 1 : 0;
}
s++;
} while (l1 != null || l2 != null);
if (addNumber == 1) {
add(l3, new ListNode(1));
}
return l3;
}
public static void add(ListNode node, ListNode addNode) {
if (node.next == null) {
node.next = addNode;
}else {
add(node.next, addNode);
}
}
}