Leetcode添加两个数字-链接列表

时间:2019-06-07 07:00:50

标签: java

我尝试测试边缘情况link1 =[5]link2 = [5]。但是,它一直告诉我NullPointerException出错。结果应该是[0,1]

我认为问题出在最后的if语句中。谁能帮我解释一下这部分有什么问题吗? 非常感谢。

提示:https://leetcode.com/problems/add-two-numbers/submissions/

我曾尝试将其放入循环中,但它也不起作用。

 /**
 * 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 a1 = l1;
        ListNode a2 = l2;
        ListNode result = new ListNode(0);
        int carry = 0;
        int sum = 0;
        ListNode head = new ListNode(0);
        head = result;
        while ( a1 != null || a2 != null )
        {
            if ( a1 == null)
            {
                sum = 0 + a2.val;
                result = new ListNode(sum);
                result = result.next;
                a2 = a2.next;
            }
            else if (a2 == null)
            {
                sum = a1.val + 0;
                result = new ListNode(sum);
                result = result.next;
                a1 = a1.next;
            }

            // sum = (a1 !=null ? a1.val : 0) + a2 != null? a2.val : 0;
            // result = result.next = new ListNode(sum);
            else
            {
                if ((a1.val + a2.val < 10) && carry == 0)
                {
                    sum = a1.val + a2.val;
                    result = result.next = new ListNode(sum);
                    a1 = a1.next; a2 = a2.next;
                }
                else if (a1.val + a2.val < 10 && carry == 1)
                {
                    sum = a1.val + a2.val + 1;
                    result = result.next = new ListNode(sum);
                    a1 = a1.next; a2 = a2.next;
                    carry = 0;
                }
                else
                {
                    int quo = (a1.val + a2.val) % 10;
                    result = result.next = new ListNode(quo);
                    carry = 1;
                    a1 = a1.next; a2 = a2.next;
                }
            }
    }
        if (a1 == null && a2 == null && carry == 1)
            result  = result.next = new ListNode(1);
        return head.next;
    }
}

1 个答案:

答案 0 :(得分:0)

可能的解决方案之一,通过了所有测试:

public class Solution {
    public 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;
    }
}