【チェーンテーブル】B 014_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
方法1:空のチェーンテーブル値が0
文字列に加えて、1つのチェーンテーブルが空でない限りループし続け、チェーンテーブルの空のノードの値はデフォルトで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:空間の使用を制限しないで、2つのスタックでそれぞれ2本のチェーンテーブルの値を記憶することができて、最後に方法でチェーンテーブルを一回の方法でスタックを遍歴する