题目
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1
输入: l1 = [9,2,4,3], l2 = [5,6,4]
输出: [9,8,0,7]
解题思路
正常情况单向链表只能从头到尾,不能从尾到头;
但是计算两数之和有需要从链表尾部开始计算,怎么处理呢
常规思路,反转链表
假设链表l1为:
graph LR
9 --> 2 --> 4 --> 3
反转后
graph LR
3 --> 4 --> 2 --> 9
不懂如何反转链表???
点击我,带你反转链表
graph LR
5 --> 6 --> 4
反转后
graph LR
4 --> 6 --> 5
需要计算反转后的l1,l2即可得到正确数值
graph LR
4 --> 6 --> 5
graph LR
3 --> 4 --> 2 --> 9
结果
graph LR
7 --> 0 --> 8 --> 9
在将结果反转
graph LR
9 --> 8 --> 0 --> 7
即可得到结果
代码
var addTwoNumbers = function(l1, l2) {
let node1 = reverse(l1);
let node2 = reverse(l2);
const result = new ListNode(-1);
let header = result;
let sign = 0
while(node1 || node2){
const n = ((node1||{}).val || 0) + ((node2||{}).val || 0) + sign
sign = n>9?1:0;
header.next = new ListNode(n%10);
header = header.next;
if(node1) node1 = node1.next
if(node2) node2 = node2.next
}
if(sign) header.next = new ListNode(1)
return reverse(result.next)
function reverse(node){
let pro = null;
let c = node;
let next = node.next
while(c){
c.next = pro;
pro = c;
c = next
next = next?next.next:null
}
return pro
}
};