leetCode刷题(使用链表做加法)

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
关键是获取最后一个node节点
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
function listNode(val) {
    this.val = val;
    this.next = null;
}
var addTwoNumbers = function(l1, l2) {
    var addp=l1,addn=l2,addpArr=[],addnArr=[],result;
    while(addp){
        addpArr.push(addp.val);
        addp=addp.next;
    }
    while(addn){
        addnArr.push(addn.val);
        addn=addn.next;
    }
	debugger
    var resultArr=[];
	for(var j=0;j=10&&i==Math.max(addpArr.length,addnArr.length)-1){
            addpArr[i+1]=0;
            addnArr[i+1]=0;
        }
        if(addpArr[i]+addnArr[i]>=10){
            addpArr[i+1]+=1;
			resultArr.push(addpArr[i]+addnArr[i]-10);
        }else{
			resultArr.push(addpArr[i]+addnArr[i]);
		}
    }
//  我认为应该返回result才是对的,但是事实上返回resultArr才是对的    
//     var result=new listNode("");
// 	result.val=resultArr[0];
// 	result.next=lastNode;
// 	var lastNode;
// 	for(var i = 1;i

  

转载于:https://www.cnblogs.com/windseek/p/8624446.html

你可能感兴趣的:(leetCode刷题(使用链表做加法))