当一个人为了对结构起作用而遍历一个链接结构时(即:将一个节点作为一个简单的例子插入到一个简单的链表中),就可以通过在结构中推一个双指针来获得最佳算法。如果使用单个引用,则必须为空根和/或尾部插入编写一个或多个特殊情况。
node_type **dp = &root;
while(*dp && /insertion point not reached/)
dp=&(*dp)->next;
当我退出循环时,* dp是插入列表的点;我持有对象链接的引用。此引用可能是根,结构末尾的空对象或任何其他节点。随着结构变得越来越复杂,随着对特殊情况的需求呈指数级增长,对双引用的需求变得更加明显。
如何在Visual Basic中实现双引用?
注意:链接列表位仅作为示例...我知道:围绕这个简单的问题有很多方法。
答案 0 :(得分:1)
请原谅C#,我的VB.NET相当生疏。在C#/ VB.NET中安全地进行双引用的唯一方法是在方法中使用ref
参数。
using System;
namespace Test
{
class Program
{
private static void Main(string[] args)
{
// Create an example root node. This example still works when root
// is null.
Node root = new Node() { next = new Node() };
// Setup a Node that contains a pointer to root. This variable will
// not be destroyed by iteration and rp.next will always be root
// after iteration, even if root started as null.
Node rp = new Node() { next = root };
// Initialize the iterator to the root pointer.
Node dp = rp;
// Define a new node to be inserted for this example.
Node nn1 = new Node();
Node nn2 = new Node();
// Iterate by calling DoWork until a null reference is returned.
// Note that a reference to dp.next is passed to the method. This
// allows the method to change what dp.next points to. The node to
// insert is also given to the method. You could easily change this
// second parameter to be an action that works on the desired node.
while(null != (dp = DoWork(ref dp.next, nn1))) { }
dp = rp;
while(null != (dp = DoWork(ref dp.next, nn2))) { }
// Force root to be assigned. If root did not start as null this
// line is unnecessary.
root = rp.next;
}
private static Node DoWork(ref Node node, Node nn)
{
// Logic to determine if the insertion point is not reached. For
// this example the new node is always inserted just before the tail.
bool logic = null != node && null != node.next;
// Check node and logic. Return the node to continue iterating.
if(null != node && logic)
{
return node;
}
// Insertion logic here. For the example the new node is inserted
// into the linked list.
nn.next = node;
node = nn;
// Return null to signify that 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;
}
}
}
答案 1 :(得分:-1)
经过研究,我得出的结论是,答案类似于:“如果你方式太醉,不开车但是你真的需要开车怎么办?”答:这很简单,不要开车。
垃圾收集语言,例如:Visual Basic,不能区分收集的变量和对它的引用。我需要双重参考吗?我当然是了!有没有办法在垃圾收集语言中获得一个?不......如果我可以做这样的话,它会破坏垃圾收集器。
嗯,我希望有一些神奇的答案......喝多少咖啡?我只需要忍受这样一个事实,即在Visual Basic中没有像“双引用”这样的动物,并找到解决方法。
史密斯