i got a little problem. The following code inserts a given element in a sorted LinkedList. If i run this method as a void-method, the result is wrong. For example the list before is 1,2,3. If i start the method with 2 as insert, it works correctly. but if i insert a number smaller 1 or bigger 3, it doesn't work.
if i change the method to give back the head of the new linked list, it works perfectly.
whats wrong here?
Here you can see both codes:
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;
}
thanks for your help!
In your code, you change the value of head
:
if (last == null){
head = add;
}
That changes the argument 's value. It has no effect on the calling code's version of that. So for instance, if the calling code was
insertIter(foo, 1, someComparator);
...changing head
in insertIter
has no effect whatsoever on the value of foo
; foo
still contains the old value.
Since you might have to change head
, you'll need to return it (as you've discovered), and do this:
foo = insertIter(foo, 1, someComparator);
Remember that variables contain values, and it's the value, not the variable, that is passed into a method. The value related to an object is called an object reference. It's akin to a number that the JVM uses to locate the object in memory. foo
above might contain Ref55465
(we never see these actual values), and even if you change the value in head
from Ref55465
to Ref66548
, foo
still contains Ref55465
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.