單鏈表表示的兩個數相加

原題

  You are given two linked lists representing two non-negative numbers. 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.
  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 0 -> 8node

題目大意

  有兩個單鏈表,表明兩個非負數,每個節點表明一個數位,數字是反向存儲的,即第一個結點表示最低位,最後一個結點表示最高位。求兩個數的相加和,而且以鏈表形式返回。git

解題思路

  對兩個鏈表都從第一個開始處理,進行相加,結果再除以10求商,做爲下一位相加的進位,同時記錄餘數,做爲本位的結果,一直處理,直到全部的結點都處理完。spa

代碼實現

/**
     * 002-Add Two Numbers (單鏈表表示的兩個數相加)
     * @param l1 第一個數
     * @param l2 第二個數
     * @return 結果
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {
            return l1;
        }

        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode root = new ListNode(0); // 頭結點
        ListNode r = root;
        root.next = l1;

        int carry = 0; // 初始進位
        int sum;
        while (p1 != null && p2 != null) {
            sum = p1.val + p2.val + carry;
            p1.val = sum % 10; // 本位的結果
            carry = sum / 10; // 本次進位

            r.next = p1;
            r = p1; // 指向最後一個相加的結點
            p1 = p1.next;
            p2 = p2.next;

        }

        if (p1 == null) {
            r.next = p2;
        } else {
            r.next = p1;
        }

        // 最後一次相加還有進位
        if (carry == 1) {
            // 開始時r.next是第一個要相加的結點
            while (r.next != null) {
                sum = r.next.val + carry;
                r.next.val = sum % 10;
                carry = sum / 10;
                r = r.next;
            }

            // 都加完了還有進位,就要建立一個新的結點
            if (carry == 1) {
                r.next = new ListNode(1);
            }
        }

        return root.next;
    }
}
相關文章
相關標籤/搜索