【链表】B014_LC_链表求和(空链表值为 0 / 进阶问题)

一、Problem

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295.
Output: 2 -> 1 -> 9. That is, 912.
Follow Up: Suppose the digits are stored in forward order. Repeat the above problem.

二、Solution

方法一:空链表值为 0

和字符串相加一个思想,只要有一个链表不空就一直循环下去,链表的空节点的值默认为 0

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int ca = 0;
        ListNode dead = new ListNode(-1), cur = dead;

        while (l1 != null || l2 != null) {
            int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
            if (ca > 0) {
                sum += ca;
                ca = 0;
            }
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
            ca = sum / 10;
        }
        if (ca > 0) 
            cur.next = new ListNode(ca);
        return dead.next.next;
    }
}
复杂度分析
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

进阶

Q:如果数位是正向存放,怎么办?
A:没有限制空间的使用,就可以用两个栈分别存储两条链表的值,最后用方法一遍历链表的方式去遍历栈

你可能感兴趣的:(#,链表)