题解 | #两个链表生成相加链表#

两个链表生成相加链表

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

用栈的方法解决该问题 javascript版本

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
function addInList( head1 ,  head2 ) {
    // write code here
    var stack1 = [];
    var stack2 = [];
    var p1 = head1;
    var p2 = head2;
    while(p1){
        stack1.push(p1.val);
        p1 = p1.next;
    }
    while(p2){
        stack2.push(p2.val);
        p2 = p2.next;
    }
    var res = null;
    var up = 0;
    while(stack1.length || stack2.length){
       var n1 = stack1.length === 0 ? 0 : stack1.pop();
       var n2 = stack2.length === 0 ? 0 : stack2.pop();
       var currSum = n1 + n2 + up;
       var tmp = new ListNode(currSum%10);
        tmp.next = res;
        res = tmp;
        up = Math.floor(currSum/10);
    }
    if(up){
        var tmp = new ListNode(up);
        tmp.next = res;
        res = tmp;
    }
    return res;

}
module.exports = {
    addInList : addInList
};
全部评论

相关推荐

WhiteAlbum...:学院本2中大厂垂直实习➕acm比赛 秋招0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务