單連結串列逆位表示的 2 個整數求和

LJ2016發表於2019-09-04

遞迴寫法

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 協議》,轉載必須註明作者和本文連結

相關文章