单链表逆位表示的 2 个整数求和

递归写法

function Node(value)
{
    this.value = value;
    this.next = null;
}

function print_list(list)
{
    let a = [];
    let p = list;
    while(p){
        a.push(p.value);
        p = p.next;
    }
    console.log(a);
}

function linklist_sum(l1, l2, carry = 0)
{
    let a, b;
    let node;

    if(!l1 && !l2){
        if(carry == 0) return null;
        else{
            a = 0;
            b = 0;
            node = new Node((a + b + carry ) % 10);
            carry = Math.floor((a + b + carry ) / 10);

            node.next = linklist_sum(null, null, carry);
            return node;
        }
    }else if(l1 && l2){
        a = l1.value;
        b = l2.value;
        node = new Node((a + b + carry ) % 10);
        carry = Math.floor((a + b + carry ) / 10);

        node.next = linklist_sum(l1.next, l2.next, carry);
        return node;
    }else if(!l1 && l2){
        a = 0;
        b = l2.value;
        node = new Node((a + b + carry ) % 10);
        carry = Math.floor((a + b + carry ) / 10);

        node.next = linklist_sum(null, l2.next, carry);
        return node;
    }else if(l1 && !l2){
        a = l1.value;
        b = 0;
        node = new Node((a + b + carry ) % 10);
        carry = Math.floor((a + b + carry ) / 10);

        node.next = linklist_sum(l1.next, null, carry);
        return node;
    }
}

l1 = new Node(9);
l2 = new Node(5);
var l = linklist_sum(l1, l2);
print_list(l);

迭代写法:

function linklist_sum(l1, l2)
{
    let carry = 0;
    let a, b;
    let node;
    let l = null;
    let p = l;
    while(l1 || l2 || carry != 0){
        a = l1 ? l1.value : 0;
        b = l2 ? l2.value : 0;
        node = new Node((a + b + carry) % 10);

        if(l == null){
            l = p = node;
        }else{
            p.next = node;
            p = p.next;
        }
        carry = Math.floor((a + b + carry) / 10);
        l1 = l1 ? l1.next : null;
        l2 = l2 ? l2.next : null;
    }
    return l;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!