Why does creating a wrapper object work in Java instead of passing a local reference? -


i looking @ code in java convert sorted linked list balanced bst , wanted know why implementation #1 doesn't work. java reason when create wrapper object , pass around works when use local reference doesnt ? objects still created on heap right.

implementation #1

binarytree.node sortedlisttobst(mylist.node w, int start, int end)      {           if (start > end) return null;           int mid = start + (end - start) / 2;           binarytree.node left = sortedlisttobst(w, start, mid-1);           binarytree.node parent = new binarytree.node(w.getval());           w = w.getnext();           binarytree.node right = sortedlisttobst(w, mid+1, end);           parent.left = left;           parent.right =right;           return parent;         }            binarytree.node sortedlisttobst(mylist.node head, int n) {            return sortedlisttobst(head, 0, n-1);         } 

implementation #2

    binarytree.node sortedlisttobstwrapper(wrapper w, int start, int end)      {           if (start > end) return null;           int mid = start + (end - start) / 2;           binarytree.node left = sortedlisttobstwrapper(w, start, mid-1);           binarytree.node parent = new binarytree.node(w.node.getval());           w.node = w.node.getnext();           binarytree.node right = sortedlisttobstwrapper(w, mid+1, end);           parent.left = left;           parent.right =right;           return parent;         }            binarytree.node sortedlisttobstwrapper(mylist.node head, int n) {              wrapper w = new wrapper();                 w.node = head;           return sortedlisttobstwrapper(w, 0, n-1);         } 

the key line is:

w.node = w.node.getnext(); 

in first implementation, 'advancing pointer' in recursive levels forgotten; parent callers not see position having advanced.

if wanted make first approach work, you'd need carry around iterator/ or have containing class embody iterator of sort, advancement thru source-list while building lhs returned parent & used build rhs.. before being returned grandparent, etc.

if language had multi-value returns, return (binarytree.node, mylist.node) , use second field in tuple track work-progress.

essentially, you've hacked solution -- clean & correct if make w iterator, opposed unstructured thing munge.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -