繁体   English   中英

C# 参考说明

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM