对数组进行循环操作时使用哑结点可以使循环体内逻辑更加统一
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(0);
ListNode result = l3;
int carry = 0;
while(l1 != null || l2 != null) {
int n1 = l1 == null ?0 : l1.val;
int n2 = l2 == null ?0 : l2.val;
int sum = n1 + n2 + carry;
l3.next = new ListNode(sum % 10);
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
l3 = l3.next;
}
if (carry > 0) {
l3.next = new ListNode(1);
}
return result.next;
}
}