题目描述:

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。

解析:

栈的思想 alt

1.首先将两个链表入栈,然后当两个栈不为空时,分别取出一个值
2.定义一个进位数carry,和curr一个链表节点,当两个栈不为空时,从两个栈中取出的值相加, 之后需要加上进位
3.定义一个节点需要对sum取模,进位同时更新,然后再是新的节点指向curr,curr再移动到新的节点
4.如果进位不为空,则把carry定义为一个节点,使这个节点指向curr,curr再移动到这个节点
5.最后返回curr即可

Java:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        while(l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while(l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        int carry = 0;
        ListNode curr = null;
        while(!stack1.empty() || !stack2.empty()) {
            int sum = 0;
            if(!stack1.empty()) {
                sum += stack1.pop();
            }
            if(!stack2.empty()) {
                sum += stack2.pop();
            }
            sum += carry;
            ListNode node = new ListNode(sum % 10);
            carry = sum / 10;
            node.next = curr;
            curr = node;
        }
        if(carry != 0) {
            ListNode node = new ListNode(carry);
            node.next = curr;
            curr = node;
        }
        return curr;
    }

JavaScript:

var addTwoNumbers = function(l1, l2) {
    const stack1 = [], stack2 = [];
    while(l1 !== null) {
        stack1.push(l1.val);
        l1 = l1.next;
    }
    while(l2 !== null) {
        stack2.push(l2.val);
        l2 = l2.next;
    }
    let carry = 0, curr = null;
    while(stack1.length !== 0 || stack2.length !== 0) {
        let sum = 0;
        if(stack1.length !== 0) {
            sum += stack1.pop();
        }
        if(stack2.length !== 0) {
            sum += stack2.pop();
        }
        sum += carry;
        const node = new ListNode(sum % 10);
        carry = Math.floor(sum / 10);
        node.next = curr;
        curr = node;
    }
    if(carry !== 0) {
        const node = new ListNode(carry);
        node.next = curr;
        curr = node;
    }
    return curr;
};