vb.net - Linked Structures in Visual Basic; is it possible to implement a double reference? -
when 1 traversing linked structure intent of acting upon structure (i.e.: inserting node simple linked list trivial example,) 1 obtains best algorithm pushing double pointer through structure; if single reference used, 1 must write 1 or more special cases null roots and/or tail insertions.
node_type **dp = &root; while(*dp && /insertion point not reached/) dp=&(*dp)->next;
when fall out of loop, *dp point of insertion list; i'm holding reference object's link. reference might root, null object @ end of structure, or other node. structure becomes more complex, need double-reference becomes more pronounced need special cases tends grow exponentially.
how 1 implement double-reference in visual basic?
note: linked list bit serves example... know: there lots of ways around simple issue.
please excuse c#, vb.net rather rusty. way safely double references in c#/vb.net using ref
parameter method.
using system; namespace test { class program { private static void main(string[] args) { // create example root node. example still works when root // null. node root = new node() { next = new node() }; // setup node contains pointer root. variable // not destroyed iteration , rp.next root // after iteration, if root started null. node rp = new node() { next = root }; // initialize iterator root pointer. node dp = rp; // define new node inserted example. node nn1 = new node(); node nn2 = new node(); // iterate calling dowork until null reference returned. // note reference dp.next passed method. // allows method change dp.next points to. node // insert given method. change // second parameter action works on desired node. while(null != (dp = dowork(ref dp.next, nn1))) { } dp = rp; while(null != (dp = dowork(ref dp.next, nn2))) { } // force root assigned. if root did not start null // line unnecessary. root = rp.next; } private static node dowork(ref node node, node nn) { // logic determine if insertion point not reached. // example new node inserted before tail. bool logic = null != node && null != node.next; // check node , logic. return node continue iterating. if(null != node && logic) { return node; } // insertion logic here. example new node inserted // linked list. nn.next = node; node = nn; // return null signify iteration has completed. return null; } } [system.diagnostics.debuggerdisplay("{id} - {next}")] class node { private static int sid; public int id; public node next; public node() { id = ++sid; } } }
Comments
Post a Comment