【问题标题】:Globally Declared Variable Returning Null After Method Call方法调用后全局声明的变量返回 Null
【发布时间】:2020-07-09 17:20:27
【问题描述】:

我正在尝试在 C# 中创建一个 LinkedList。我是新来的。你能帮帮我吗? 我要做的是:我创建了 Node 类型的 head 和 lastNode 变量,并尝试通过 GetLastNode() 方法检查 lastnode 来将节点添加到每个前一个节点。虽然,每次我尝试添加第二个元素时,head 在到达GetLastNode() 时变为空。我不确定为什么会这样。请帮助我理解我遗漏的概念。

class MyLinkedList
    {
        Node head, lastNode; 
        
        public void Add(int new_value)
        {
            Node new_node = new Node(new_value);                
            MyLinkedList obj = new MyLinkedList();
            lastNode = obj.GetLastNode();
            if(lastNode == null)
            {
                lastNode = new_node;
                this.head = new_node;
            }                  
            
            else
            {
                lastNode.next = new_node;
            }
        }
        public Node GetLastNode()
        {
            Node currentNode = this.head;
            if (currentNode == null)
                lastNode = currentNode;
            else
                while (currentNode != null)
                {
                    lastNode = currentNode;
                    currentNode = currentNode.next;
                }
            
            return lastNode;

        }
    }

【问题讨论】:

  • 请告诉我们Node类
  • 每次调用Add() 时,您似乎都在创建一个新的链表。这是为什么呢?
  • 您的head 字段不是全局的,它是MyLinkedList 的属性,每次您创建新的MyLinkedList,调用GetLastNode() 将使用您的新MyLinkedList 的@ 987654330@字段

标签: c# oop data-structures linked-list


【解决方案1】:

headlastNode 不是全局的,它们是 fields,对于 MyLinkedList 的每个实例都会有所不同。在Add 中,您将创建一个新的(使用new 关键字)MyLinkedList 实例,该实例为GetLastNode() 返回null,并将此null 分配给当前lastNode,因此您将得到@ 987654332@ 为您当前的lastNodeif 之前:

MyLinkedList obj = new MyLinkedList();
lastNode = obj.GetLastNode();

我会说你可以删除这行。

另外,GetLastNode 似乎应该只返回 lastNode,因为您已经在 Add 上进行了所有需要的跟踪:

public Node GetLastNode()
{
    return lastNode;
}

【讨论】:

  • @AbhaJha 很乐意提供帮助!
猜你喜欢
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 2013-01-23
  • 2020-01-15
相关资源
最近更新 更多