1. 对应力扣题目连接
2. 实现案例代码
java
public class AddingTwoNumbers {
public static void main(String[] args) {
// 示例用例 1
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(5);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
ListNode s = addTwoNumbersNew(l1, l2);
soutListNode(s);
}
public static ListNode addTwoNumbersNew(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
// 用于表示进位
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
}
return dummy.next;
}
public static void soutListNode(ListNode l1) {
if (l1 == null) {
return;
}
System.out.println(l1.val);
soutListNode(l1.next);
}
}
/**
* 节点类
*/
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}