题目分析:
由于链表是逆序存储的数字,所以直观上从左到右的排序是个、十、百、千...,按照加法的方法,个位相加,满十进一即可。此外需要考虑当最高位相加仍然大于十,要在链接结尾新增一个进位节点。若链表不一样长,需要把长链表的后续链接上。代码如下:
/**
* 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) {
var head=null, l3 = null;
var carry = 0; //进位
while(l1 || l2) {
var n1 = l1 ? l1.val : 0;
var n2 = l2 ? l2.val : 0;
var sum = n1 + n2 + carry;
if (!head) {
head = l3 = new ListNode(sum%10);
} else {
l3.next = new ListNode(sum%10);
l3 = l3.next;
}
carry = Math.floor(sum/10); // 当前进位
// 下一位
if (l1) {
l1 = l1.next;
}
if (l2) {
l2 = l2.next;
}
}
if (carry > 0) {
l3.next = new ListNode(carry); // 最高位进位
}
return head;
}
Typescript版本:
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let head:ListNode | null = null, l3:ListNode | null = null;
let carry: number = 0;
while (l1 || l2) {
let n1:number = l1 ? l1.val : 0;
let n2:number = l2 ? l2.val : 0;
let sum:number = n1 + n2 + carry;
if (!head) {
head = l3 = new ListNode(Math.floor(sum%10));
} else {
l3.next = new ListNode(Math.floor(sum%10));
l3 = l3.next;
}
carry = Math.floor(sum/10);
if (l1) {
l1 = l1.next;
}
if (l2) {
l2 = l2.next;
}
}
if (carry > 0) {
l3.next = new ListNode(carry);
}
return head;
};