gpt4 book ai didi

java - 无效结果和特定结果之间的差异

转载 作者:行者123 更新时间:2023-12-01 20:52:21 25 4
gpt4 key购买 nike

我遇到了一个小问题。以下代码将给定元素插入已排序的 LinkedList 中。如果我将此方法作为 void 方法运行,结果是错误的。例如前面的列表是1,2,3。如果我以 2 作为插入来启动该方法,则它可以正常工作。但如果我插入一个小于 1 或大于 3 的数字,则不起作用。

如果我改变方法来返回新链表的头,它就可以完美地工作。

这里出了什么问题?

在这里您可以看到这两个代码:

static void insertIter (simplyLinkedList head, int insert, Comparator cmp){

if (head == null) return;

simplyLinkedList last = null;
simplyLinkedList actual = head;
simplyLinkedList add = new simplyLinkedList(insert);

while (actual != null){

if (cmp.compareInt(insert, actual.key) == -1 || cmp.compareInt(insert, actual.key ) == 0){

add.next = actual;

if (last == null){

head = add;

}
else {

last.next = add;

}
return;
}
last = actual;
actual = actual.next;
}
if (actual == null){

last.next = add;
add.next = null;
}

return;
}




static simplyLinkedList insertIter (simplyLinkedList head, int insert, Comparator cmp){

if (head == null) return null;

simplyLinkedList last = null;
simplyLinkedList actual = head;
simplyLinkedList add = new simplyLinkedList(insert);

while (actual != null){

if (cmp.compareInt(insert, actual.key) == -1 || cmp.compareInt(insert, actual.key ) == 0){

add.next = actual;

if (last == null){

head = add;

}
else {

last.next = add;

}
return head;
}
last = actual;
actual = actual.next;
}
if (actual == null){

last.next = add;
add.next = null;
}

return head;
}

感谢您的帮助!

最佳答案

在代码中,更改 head 的值:

if (last == null){
head = add;
}

这会改变参数的值。它对调用代码的版本没有影响。例如,如果调用代码是

insertIter(foo, 1, someComparator);

...在 insertIter 中更改 headfoo 的值没有任何影响; foo 仍然包含旧值。

由于您可能需要更改 head,因此您需要返回它(正如您所发现的),然后执行以下操作:

foo = insertIter(foo, 1, someComparator);

请记住,变量包含值,传递到方法中的是值,而不是变量。与对象相关的值称为对象引用。它类似于 JVM 用于在内存中定位对象的数字。上面的 foo 可能包含 Ref55465 (我们永远不会看到这些实际值),即使您将 head 中的值从 Ref55465Ref66548foo 仍包含 Ref55465

关于java - 无效结果和特定结果之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43027175/

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