思路
用两个栈分别存储两个链表,用 头插法 构建结果链表。
代码
function addInList( head1 , head2 ) {
let stack1 = [];
let stack2 = [];
let p = head1;
let q = head2;
while(p){
stack1.push(p.val);
p = p.next;
}
while(q){
stack2.push(q.val);
q = q.next;
}
let jinwei = 0;
let head = new ListNode(0);
while(stack1.length>0 || stack2.length>0){
let a = stack1.length==0 ? 0 : stack1.pop();
let b = stack2.length==0 ? 0 : stack2.pop();
let sum = a + b + jinwei;
let temp = new ListNode(sum%10);
jinwei = Math.floor(sum/10);
let next = head.next;
head.next = temp;
temp.next = next;
}
if(jinwei>0){
let temp = new ListNode(jinwei);
let next = head.next;
head.next = temp;
temp.next = next;
}
return head.next;
}
module.exports = {
addInList : addInList
};