一、迭代
官方解法(虽然我还是喜欢递归)
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) {
ListNode pre = new ListNode();//定义头节点
ListNode node = pre;
int carry = 0;//进位
while (l1 != null || l2 != null) {//只要l1,l2中有一个不为空则循环
int x = l1 == null ? 0 : l1.val;//l1不为空则传入值
int y = l2 == null ? 0 : l2.val;//l2不为空则传入值
int sum = x + y + carry;
carry = sum / 10;//取进位
sum = sum % 10;//取个位值
node.next = new ListNode(sum);//将值传入下一个节点
node = node.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry == 1) {//最后一位也需进位时则补最高位为1
node.next = new ListNode(carry);
}
return pre.next;
}
}
二、递归
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) {
return add(l1, l2, 0);
}
public ListNode add(ListNode l1, ListNode l2, int carry) {
ListNode listNode = new ListNode();
if (l1 != null || l2 != null) {//只要l1,l2中有一个不为空则进入递归
int x = l1 == null ? 0 : l1.val;//l1不为空则传入值
int y = l2 == null ? 0 : l2.val;//l2不为空则传入值
int sum = x + y + carry;
carry = sum / 10;//取进位
listNode.val = sum % 10;//取个位值传入
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
listNode.next = add(l1, l2, carry);//传值递归
return listNode;
}
if (carry == 1) {//最后一位也需进位时则补最高位为1
listNode = new ListNode(carry);
return listNode;
} else {
return null;
}
}
}