分析Add Two Numbers的JS解法

NO IMAGE

原題如下:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

意思就是數字被逆序拆分儲存在連結串列的各個節點中,現有兩條連結串列,要將這兩條連結串列相加返回新的連結串列。
以示例來說原數字為342和465,所以相加結果為807。

var addTwoNumbers = function(l1, l2) {  
  const res = test(l1,l2,[],false);
  return res;
};  

var test = function(l1,l2,res,overflow=false){
    res = res||[];
    l1=l1||{val:0,next:null};//這裡判斷傳入的陣列是否存在
    l2=l2||{val:0,next:null};//如果不存在就給他賦值後面的物件

    //這裡計算想加後的結果,Number() 函式把物件的值轉換為數字
    const val = l1.val l2.val Number(overflow);

    if(val>=10){
        res.push(val%10);
        overflow=true;
    }else{
        res.push(val);
        overflow=false;
    }
    //所有的物件都被當作 true
    //當且僅當字串為空時,該字串被當作 false
    //null 和 undefined 被當作 false
    //當且僅當數字為零時,該數字被當作 false 
    if(l1.next||l2.next||overflow){
        test(l1.next,l2.next,res,overflow);
    }

    return res;
}