题解 | #11.链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
栈、链表
将两个链表从头逐个放到stack中
从两个stack中分别取出值进行相加操作,注意如果产生进位则放到下一次中,因此引入jinwei
这个变量
注意,两个stack均为空后,还要再次判断一下是否有进位
function addInList( head1 , head2 ) {
let stack1 = new Array();
let stack2 = new Array();
while(head1 != null){
stack1.push(head1);
head1 = head1.next;
}
while(head2 != null){
stack2.push(head2);
head2 = head2.next;
}
let jinwei = 0;//之前的进位
let pHead = new ListNode(-1);
let pre = pHead;
while(stack1.length!=0 || stack2.length!=0){
let node1 = stack1.pop();
let node2 = stack2.pop();
let val1 = node1 ? node1.val : 0;
let val2 = node2 ? node2.val : 0;
let falseValue = val1 + val2 + jinwei;
let trueValue = falseValue % 10;
jinwei = (falseValue - trueValue) / 10;
let node = new ListNode(trueValue);
node.next = pre.next;
pre.next = node;
}
if(jinwei == 1){
let temp = new ListNode(1);
temp.next = pHead.next;
pHead.next = temp;
}
return pHead.next;
}
module.exports = {
addInList : addInList
};