题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/67afb281447b4f049828851ac1814d80.png)
代码
class Solution {
public ListNode addTwoNumbers(ListNode head1, ListNode head2) {
ListNode cur = null;
ListNode ans = null;
int carry = 0;
for(int sum,val;
head1 != null || head2 != null;
head1 = head1 == null ? null : head1.next,
head2 = head2 == null ? null : head2.next
){
sum = (head1 == null ? 0 : head1.val)+(head2 == null ? 0 : head2.val) + carry;
val = sum % 10;
carry = sum / 10;
if(ans == null){
ans = new ListNode(val);
cur = ans;
}else{
cur.next = new ListNode(val);
cur = cur.next;
}
}
if(carry == 1){
cur.next = new ListNode(1);
}
return ans;
}
总结
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/cd613411f0ad4ef39c4a589cca20a0bc.png)