gpt4 book ai didi

java - 将两个表示为链表的数字相加

转载 作者:行者123 更新时间:2023-12-01 11:29:22 24 4
gpt4 key购买 nike

我正在尝试实现一个函数来添加两个表示为反向链接列表的数字。在我看来,代码是正确的,但在提供两个仅由一个数字组成的链表的输入时 [5] 。输出是 [0],但它应该是 [0]->[1]

示例第一个列表: 5->6->3//代表数字 365 第二个列表: 8->4->2//代表数字 248 。结果列表:3->1->6//代表数字 613

有人可以告诉我我在逻辑上做错了什么吗?`

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//find length
int carry = 0;
ListNode sum = null;
int x = 0;
ListNode top = new ListNode(0);
while(l1 != null || l2 != null){
sum = new ListNode((l1.val+l2.val+carry)%10);
// sum.val = (l1+l2+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l1.val+l2.val)/10;
l1 = l1.next;
l2 = l2.next;
sum = sum.next;
}
if(l1 == null && l2 == null){
//return top;

}else if(l1 != null && l2 == null){
while(l1 != null){
sum = new ListNode((l1.val+carry)%10);
// sum.val = (l1+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l1.val)/10;
l1 = l1.next;
sum = sum.next;
}
//return top;
}else{
while(l1 != null){
sum = new ListNode((l2.val+carry)%10);
// sum.val = (l2+carry)%10;
if(x==0){
top.next = sum;
x++;
}
carry = (l2.val)/10;
l2 = l2.next;
sum = sum.next;
}
//return top;
}
if(carry == 1){
sum = new ListNode(1);

sum = sum.next;
}
return top.next;
}
}`

最佳答案

这是一个解决方案(对 ListNode 使用“value”方法):

package so30544570;

public class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return ListNode.valueOf(l1.value() + l2.value());
}

public static void main(String[] args) {
ListNode l1 = ListNode.valueOf(365);
ListNode l2 = ListNode.valueOf(248);
System.out.println("l1 = " + l1);
System.out.println("l2 = " + l2);
System.out.println("l1 + l2 = " + addTwoNumbers(l1, l2));
}
}

ListNode:

package so30544570;

public class ListNode {
private int val;
private ListNode next;

private ListNode(int x) {
val = x;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder().append(val);
if (next != null) {
sb.append(" -> ").append(next.toString());
}
return sb.toString();
}

public int value() {
int result = val;
if (next != null) {
result += 10 * next.value();
}
return result;
}

public static ListNode valueOf(final int i) {
ListNode root = new ListNode(i % 10);
if (i / 10 > 0) {
root.next = ListNode.valueOf(i / 10);
}
return root;
}
}
<小时/>

输出:

l1 = 5 -> 6 -> 3

l2 = 8 -> 4 -> 2

l1 + l2 = 3 -> 1 -> 6

<小时/>

注意:此解决方案避免求和计算,我们只需为求和重新创建一个ListNode

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

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