[英]C# reference clarification
幾天前,我遇到了一件有趣的事情,但我無法理解它,或者說我有一種感覺,但我不確定。
具有以下鏈表實現:
public class LinkedList<T>
{
private class Node
{
public T Value;
public Node? Next;
public Node(T value) => (Next, Value) = (null, value);
}
private Node? head;
public LinkedList()
{
head = null;
}
public void InsertBack1(T value)
{
if (head == null)
{
head = new Node(value);
}
else
{
Node? current = head;
while (current?.Next != null)
{
current = current.Next;
}
current.Next = new Node(value); ;
}
}
public void InsertBack2(T value)
{
Node? current = head;
while (current != null)
{
current = current.Next;
}
current = new Node(value);
}
public void Print()
{
var current = head;
while (current != null)
{
Console.Write(current.Value + " --> ");
current = current.Next;
}
}
}
通過使用InsertBack1()
方法,插入工作正常,但InsertBack2()
方法不能。 使用以下代碼段:
var list = new LinkedList<int>();
list.InsertBack1(1);
list.InsertBack1(2);
list.InsertBack2(3);
我得到以下鏈表:1 -> 2。
在InsertBack2()
方法中,代碼檢查當前節點是否為null ,如果不是,則將當前引用移動到子節點或為相應元素創建新節點。 理論上應該沒問題,但是在運行時不會插入新節點。 據我了解,當電流轉移到未初始化的孩子身上時,它會以某種方式失去頭部object 的所有參考並且不同步(假設是這樣)。
然而在InsertBack1()
方法中它只是工作,當前的 object 獲得了一個新的孩子,並且頭部object 也收到了修改。
那么參考文獻到底發生了什么?
讓我們看看調用InsertBack2(3)
時會發生什么。
public void InsertBack2(T value)
{
Node? current = head; // current now points to node 1
while (current != null)
{
// current is not null, so try next
current = current.Next;
}
// The above loop will execute two times, after which current points to null (which is the termination criteria for the loop)
current = new Node(value); // Now current is null and we assign a new instance.
}
請參閱我上面的評論。 在最后一行之后, current 包含新節點,但由於它是一個局部變量,它只是用完 scope 並被遺忘。 該節點永遠不會添加到列表中。 如果方法InsertBack3()
將是Node
的方法,則類似的實現將起作用,但這會獲得完全不同的數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.