LeetCode-2. Add Two Numbers(链表实现数字相加)

1.题目描述

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

2.我的分析思路

拿到题目,我的第一个思路是这样的:

两个链表,当链表均不为空时,将链表push到栈中,然后同时pop出来,计算栈中数字之和;计算完成后,判断将和对10求余数,放到结果的头结点中,然后把商push到栈中,然后将原始两个链表的值的next赋值为原来的两个链表。

如此递归,即可求出最终值。

不过这里面的判断方式有些问题,比如递归的条件,应该是栈不为空,或者原始的两个链表不为空。

写的代码比较冗余,就不献丑了。

3.其他的思路

现在贴出赞比较多的一个解。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode prev = new ListNode(0);
    ListNode head = prev;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        ListNode cur = new ListNode(0);
        int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
        cur.val = sum % 10;
        carry = sum / 10;
        prev.next = cur;
        prev = cur;
        l1 = (l1 == null) ? l1 : l1.next;
        l2 = (l2 == null) ? l2 : l2.next;
    }
    return head.next;
}

这里没有使用到栈的概念,增加了一个carry,也就是表示商。同时,这里面有个概念,java到底是传值和传引用,这里的head和prev就是这样。

原文地址:https://www.cnblogs.com/f-zhao/p/6380699.html