我想测试我的程序并对其进行测试,我只是将一个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);
在原始代码中,您将覆盖object1和object2的值。
这等效于您的原始代码,当然不是您想要的:
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,但从不访问它。
看来完全没有用而且毫无意义。
该方法只是将第一个列表中的值连接起来并返回它,
所以它没有做任何顾名思义的事情。