簡體   English   中英

在java中使用遞歸添加由鏈表表示的兩個數字

[英]add two numbers represented by linked lists using recursion in java

PS:有多個帖子關於添加由鏈表表示的兩個數字,但沒有一個討論遞歸解決方案。 所以請不要標記為downvote的重復。

問:給你兩個非空鏈表,代表兩個非負整數。 數字以相反的順序存儲,它們的每個節點都包含一個數字。 將兩個數字相加並將其作為鏈表返回。

您可以假設這兩個數字不包含任何前導零,除了數字 0 本身。

我的嘗試

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        recursiveAdd(l1, l2, l3, 0);
        return l3;
    }

    private void recursiveAdd(ListNode l1, ListNode l2, ListNode l3, int carryOver){
        if(l1 != null || l2!= null){
            l3.val = (l1==null?0:l1.val + (l2==null?0:l2.val) + carryOver)%10;
            l3.next = new ListNode(0);
            int carryOverNew = (l1==null?0:l1.val + (l2==null?0:l2.val) + carryOver)/10;
            recursiveAdd(l1.next, l2.next, l3.next, carryOverNew);
        }
    }
}

問題:鑒於我每次都在創建新節點,終止后總會有一個值為 0 的額外節點。如何擺脫這個? 例子:

您的輸入 [2,4,3] [5,6,4]

輸出 [7,0,8,0]

預期 [7,0,8]

在檢查您是否真的需要它之前,您可以在結果列表中創建另一個節點。 以下是解決該問題的方法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        recursiveAdd(l1, l2, l3, 0);
        return l3;
    }

    private void recursiveAdd(ListNode l1, ListNode l2, ListNode l3, int carryOver){
        //calculate value of the current digit
        l3.val = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carryOver) % 10;

        //calculate carry over to the next digit
        int carryOverNew = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carryOver) / 10;

        //take the next digit from the two operands
        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;

        //another digit is only needed if at least one these are true:
        //1. the first operand has another digit
        //2. the second operand has another digit
        //3. the carry over is more than zero
        if (l1 != null || l2 != null || carryOverNew > 0) {
            //only create another digit when it is needed
            l3.next = new ListNode(0);
            recursiveAdd(l1, l2, l3.next, carryOverNew);
        }
    }
}

此解決方案已使用示例輸入和兩個零([0] 和 [0] 正確添加到 [0])進行了測試。

編輯:我在取 l1 和 l2 的下一個元素之前添加了空檢查以防止 NullPointerExceptions,並在 l3.val 和 CarryOverNew 的計算中在第一個三元運算符 (?:) 周圍添加括號以防止錯誤結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM