主要思路就是按位相加,判断是否大于10,然后判断链表末尾是否为0
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let head = new ListNode(0);
let ret = head;
while(l1 || l2){
if(l1){
if(l2){
ret.val += l1.val + l2.val
l2 = l2.next;
}else{
ret.val += l1.val
l2 = l2
}
l1 = l1.next
}else{
if(l2){
ret.val += l2.val
l2 = l2.next
}else{
l2 = l2
}
l1 = l1
}
if(ret.val >= 10){
ret.val = ret.val % 10;
ret.next = new ListNode(1);
}
ret.next = ret.next || new ListNode(0);
if(l1 == null && l2 == null){
if(ret.next.val === 0){
ret.next = null
}
}
ret = ret.next
}
return head;
};