提交记录
思路
/*
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
*/
class Solution2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10; //表示前一位的进位
sum = sum % 10; //去除进位后
cur.next = new ListNode(sum);//尾插法(尾部插入结点)
cur = cur.next;//更新链表尾指针
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
//出while循环后
if(carry == 1) { //进位只能为1
cur.next = new ListNode(carry);
}
return pre.next;
}
}