我正在尝试实现一个函数来添加两个表示为反向链接列表的数字。在我看来,代码是正确的,但在给出输入时,两个链表只包含一个数字[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;
}
}`
答案 0 :(得分:1)
这是一个解决方案(使用ListNode
的“值”方法):
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
。
答案 1 :(得分:0)
你永远不会更新顶级。你应该做的是
if(carry == 1){
sum = new ListNode(1);
if(x==0){
top.next = sum; //This line is not executed as x = 1
x++;
}
什么是x,为什么使用它。
注意:为了便于阅读,请正确命名变量。