Reputation: 5660
This code would convert a linkedlist like : 1-> 2 -> 3 -> 4, into 1->3-2->4 (ie odd on left and even on right), except the problem caused by oddEvenSplitter
function. This code will modify references by value. How to reuse the code in such situations where input is a reference ?
public void oddEvenSplitter (Node head, Node current, Node temp) {
if (head == null) {
head = temp;
current = temp;
} else {
current.next = temp;
current = temp;
}
}
public void oddFirst( ) {
if (first == null) {
throw new NoSuchElementException();
}
Node temp = first;
Node oddhead = null;
Node odd = null;
Node evenhead = null;
Node even = null;
while (temp != null) {
if (temp.element % 2 == 0) {
oddEvenSplitter(evenhead, even, temp);
} else {
oddEvenSplitter(oddhead, odd, temp);
}
}
if (oddhead != null) {
odd.next = evenhead;
first = oddhead;
}
}
Upvotes: 0
Views: 85
Reputation: 5439
Java does not have pass by reference. It always passes values. When you pass for example oddHead
variable to oddEvenSplitter()
method, what really happens is that a copy of oddHead
variable is passed and from that point head
and oddHead
variables will be two separate variables, pointing on same object in the heap. So if you assign new value to head
variable inside your method, the other one (oddHead
) will remain unchanged. This is true for all other passed parameters as well.
As a solution you could create another object (like a DTO) and put all needed references inside it and pass it to your method. Then whenever you change those references, you will be able to get them in caller method.
Upvotes: 1