- 使用
carry记录进位情况,初始化为0
- 如果
l1节点存在,累加到carry中。
- 如果
l2节点存在,累加到carry中。
- 新节点值
carry % 10
- 下一个节点进位
carry
- 最后
carry为1,新建一个值为1的节点
Implementation
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode anchor = new ListNode(0);
ListNode head = anchor;
while (l1 != null || l2 != null) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
head.next = new ListNode(carry % 10);
carry /= 10;
head = head.next;
}
if (carry == 1)
head.next = new ListNode(1);
return anchor.next;
}
}