class BST{
private Node root;
/** Insert node x into the dictionary */
public void insert(Node z) {
insert(z, root);
}
private void insert(Node z, Node node){
if(node == null){
// error!!!!!
node = z;
return; // retun and unwind the stack
}
if(z.value < node.value)
insert(z, node.leftChild);
else
insert(z, node.rightChild);
}
[java] Recursive Functions and Passing parameters by Reference....
It has been a while since I have programmed in Java and I am having a hard time with the ways variables are passed.
So as I understand it all variables passed into functions are passed into functions by reference, though the reference itself is passed by value.
So how on earth would I do this:
The problem exists below the comment I that reads "error".
Basically I want the value pointed to by node to change to the object pointed to by z. But since the references are local to the function nothing changes.
What design practices does one follow in Java to get something like this to work?
-thanks
Instead of inserting Nodes you could try inserting the data saved in every Node and create the actual Nodes internally in the BST class. Something like:
shmoove
class Node{ void setData(NodeData data) { this.data = data; this.leftChild = new Node(); this.rightChild = new Node(); } NodeData data; Node leftChild; Node rightChild;}class BST{ private Node root = new Node(); public void insert(NodeData z) { insert(z, root); } private void insert(NodeData z, Node node) { if (node.data == null) { node.setData(z); return; } if (z.value < node.data.value) { insert(z, node.leftChild); } else { insert(z, node.rightChild); } }}
shmoove
It is, alas, a bit of an ugly hack, but you can simulate pass-by-reference by wrapping your Node in an array. That is, each argument should be a Node[1]. That way you can change what the first element of the array points to, and it'll have non-local effect.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement