gpt4 book ai didi

java - 两个数字相加链表

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:05 26 4
gpt4 key购买 nike

我有一个关于使用 LeetCode 中的链表添加两个数字的问题。下面是问题本身、我面临的问题以及我的代码。

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

问题是它打印出来:

Error:
A: 7
B: 7
C: 7
A: 10
B: 0
Exception in thread "main" java.lang.NullPointerException
at Solution.addTwoNumbers(MainClass.java:61)
at MainClass.main(MainClass.java:123)

当 result.val 为 0 时停止并调用 NullPointerException。我不太理解这部分,因为我认为在 Java 中值 0 与 NullPointerException 不同。有人可以帮我解决这个问题吗?谢谢。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
int up = 0;
ListNode num1 = l1, num2 = l2;

while (num1 != null || num2 != null){
int sum = 0;
int prevUp = 0;

if (num1 != null && num2 == null){
sum = num1.val + up;
if (sum >= 10){
up = 1;
sum = sum - 10;
}
num1 = num1.next;
result.val = sum;
result = result.next;
}
else if (num2 != null && num1 == null){
sum = num2.val + up;
if (sum >= 10){
up = 1;
sum = sum - 10;
}
num2 = num2.next;
result.val = sum;
result = result.next;
}
else{
sum = num1.val + num2.val;
System.out.println("A: "+ sum);
if (sum >= 10){
prevUp = up;
up = 1;
sum = sum - 10;
}
System.out.println("B: " + sum);
num1 = num1.next;
num2 = num2.next;
result.val = sum + prevUp;
System.out.println("C: " + result.val);
result = result.next;
}
}

return result;
}

最佳答案

由于result = result.next的原因,它抛出空指针异常,而result只有一个节点,并且您已初始化为 结果 = new listNode(0);

关于java - 两个数字相加链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com