AddTwoNumbers思路

282 阅读1分钟

AddTwoNumbers

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.
    
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers

拿到这道题的时候,发现是单向链表的结构。

考虑到是不停的向下钻(递归),数据的结构又是从低位往高位存储的,这样在进位的时候就好处理很多了。

所以接下来就是写个递归函数,处理好递归的条件。

伪代码

function reverse (l1, l2, l3) {
    if (l1 && l2) {
        处理l3数据;
        if (满足递归条件) {
            reverse(l1.next, l2.next, l3.next);    
        }
    } else if (单个链表完毕) {
        处理l3数据;
        继续递归调用reverse;
    }
}

具体实现

var addTwoNumbers = function(l1, l2) {
    const l3 = {
        val: 0,
        next: null
    };
    reverse(l1, l2, l3);
    return l3;
};
var reverse = function(l1, l2, l3) {
    if (l1 && l2) {
        if (l1.val + l2.val + l3.val >= 10) {
            l3.val += l1.val + l2.val - 10;
            l3.next = {
                val: 1,
                next: null
            };
        } else {
            l3.val += l1.val + l2.val;
            l3.next = null;
            if (l1.next || l2.next) {
                l3.next = {
                    val: 0,
                    next: null
                };
            }
            
        }
        reverse(l1.next, l2.next, l3.next);
    } else if (!l1 && l2) {
        l3.val += l2.val;
        if (l3.val >= 10) {
            l3.val = 0;
            l3.next = {
                val: 1,
                next: null
            }
        }
        if (l2.next) {
            l3.next = l3.next || {
                val: 0,
                next: null
            }
            reverse(null, l2.next, l3.next);
        }
    } else if (l1 && !l2) {
        l3.val += l1.val;
        if (l3.val >= 10) {
            l3.val = 0;
            l3.next = {
                val: 1,
                next: null
            }
        }
        if (l1.next) {
            l3.next = l3.next || {
                val: 0,
                next: null
            }
            reverse(l1.next, null, l3.next);
        }
    }
}