为什么代码只显示“1 2”?

Why is the code showing only `1 2`?

我想测试我的程序并测试它我只是将一个 ListNode 的整数转换为 String 并将这些转换连接起来。例如,如果我有:

ListNode object1;
object1 = new ListNode(2);
object1 = new ListNode(4);
object1 = new ListNode(3);

addTwoNumbers() 的输出应该是“243”(该方法的目标不同,我只是想测试一下)但它给了我“1 2”。而且 Eclipse 也不会 运行 调试器在此程序中,不知道为什么。

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }

public String addTwoNumbers(ListNode l1, ListNode l2) {
    String l1Digits = "";
    String l2Digits = "";

    while(l1 != null) {
        l1Digits += Integer.toString(l1.val) + "";
        l1 = l1.next;
    }

    while(l2 != null) {
        l2Digits += Integer.toString(l2.val) + "";
        l2 = l2.next;
    }
    return l1Digits;
}


class Tester {

  public void main(String[] args) {
    ListNode object1;
    object1 = new ListNode(2);
    object1 = new ListNode(4);
    object1 = new ListNode(3);

    ListNode object2;
    object2 = new ListNode(5);
    object2 = new ListNode(6);
    object2 = new ListNode(4);

    System.out.println(addTwoNumbers(object1, object2));

  }
  }
}

而不是这个:

ListNode object1;
object1 = new ListNode(2);
object1 = new ListNode(4);
object1 = new ListNode(3);

ListNode object2;
object2 = new ListNode(5);
object2 = new ListNode(6);
object2 = new ListNode(4);

看来你真的是这个意思:

ListNode object1;
object1 = new ListNode(2);
object1.next = new ListNode(4);
object1.next.next = new ListNode(3);

ListNode object2;
object2 = new ListNode(5);
object2.next = new ListNode(6);
object2.next.next = new ListNode(4);

在原始代码中,您覆盖了 object1object2 的值。 这等同于您的原始代码,当然不是您想要的:

ListNode object1 = new ListNode(3);
ListNode object2 = new ListNode(4);

要创建更长的列表,这可能会很乏味。 您可以创建一个辅助方法来简化操作,例如:

ListNode createList(int...values) {
    if (values.length == 0) {
        return null;
    }
    ListNode head = new ListNode(values[0]);
    ListNode node = head;
    for (int i = 1; i < values.length; ++i) {
        node.next = new ListNode(values[i]);
        node = node.next;
    }
    return head;
}

这将允许您将顶部的第一个代码替换为:

ListNode object1 = createList(2, 4, 3);
ListNode object2 = createList(5, 6, 4);

顺便说一句,您的程序中还有其他问题。 在 addTwoNumbers 中,您分配给 l2Digits 但永远不会访问它。 它似乎完全未使用且毫无意义。 该方法只是将第一个列表中的值和 returns 连接起来, 所以它没有做任何它的名字所暗示的事情。

每次您为 object1 分配新值时,您都在隐式删除所有先前分配的值。您应该通过分配 next 字段将节点附加到 LinkNode 的后面。

你应该在 ListNode 中有一个类似于 addToTail 的方法。

public class ListNode {

    // ... all the fields and methods you already have

    public void addToTail(ListNode newNode) {
        if (this == null) {
            this = newNode;
            return;
        }
        ListNode tmp = this;
        // traverse to the tail node
        while(tmp.next) { tmp = tmp.next; }
        tmp.next = newNode;
        return;
    }
}

ListNode object1;
object1.addToTail(new ListNode(2)); // (2)
object1.addToTail(new ListNode(4)); // (2) -> (4)
object1.addToTail(new ListNode(3)); // (2) -> (4) -> (3) .. and so on