For example I make the recursive call defined below. The method finds the kth element from the last. If found, it assigns the current node to the object I pass to the recursive call. For some reason the node kth is null. Can you not do things this way? And why?
public void findKthFromLast(Node head, int k){
Node kth;
recrusiveHelper(head, k, kth);
System.out.println(kth.data); //this is null
}
public int recursiveHelper(Node n, int k, Node kthFromLast){
(if n == null){
return 0;
}
val = 1 + recursiveHelper(n.next, k, kthFromlast);
if(k == val){
kthFromLast = n;
}
return val;
}
Firstly, that code shouldn’t compile because
kthis not initialized and so cannot be used as argument for therecursiveHelpermethod call.Secondly, any changes to the references in a called method are not propagated to the caller in Java, i.e.
Output:
The reason is, in
calledMethod1you are merely changing whatbufferreference points to but not making any changes to whatbufferreference was pointing when the method was called. IncalledMethod2, you are making changes to the object referred bybufferand hence the changes are visible in the caller.If you are someone coming from
CorC++background, this is equivalent to assigning to a pointer argument in a called method which doesn’t affect what was passed in the caller.