问题描述:
Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output:7 -> 0 -> 8
Explanation:342 + 465 = 807.
代码:
/**
* 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 Nhead = new ListNode(0);
var head = Nhead;
var plus = 0;
while(l1 || l2 || plus) {
var temp = plus;
if(l1!=null){
temp += l1.val;
l1 = l1.next;
}
if(l2!=null){
temp += l2.val;
l2 = l2.next;
}
plus = parseInt(temp/10);
head.next = new ListNode(temp%10);//head值变了, Nhead也变了
head = head.next; //head指向了下一个节点 但是Nhead没变
}
return Nhead.next;
};
网友评论