/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
if (l1.val == 0 && l1.next === null) return l2
if (l2.val == 0 && l2.next === null) return l1
var x,y = 0;
var head = new ListNode(0);
let ptr = head;
while(l1 || l2){
x = l1.val + l2.val + y;//这步至关重要的,本次运算值包含三个部分 加数 被加数 进位值 注意进位值需记录
y = parseInt(x/10);
ptr.val = x%10;
if (l1.next === null && l2.next === null && y != 1) return head;
if (l1.next === null) l1.next = new ListNode(0);//高位添零
if (l2.next === null) l2.next = new ListNode(0);
ptr = ptr.next = new ListNode();
l1 = l1.next;
l2 = l2.next;
}
};
|