【发布时间】:2020-03-14 18:51:29
【问题描述】:
我正在尝试将一个节点添加到单链表的末尾。但我不断收到 NullReferenceException。我已经尝试了一切,但我无法让它工作。代码背后的想法是继续循环遍历列表,直到我们到达 null(这标志着链表的末尾),然后我们在末尾添加一个新节点。 所以问题是我为什么会得到这个,我怎样才能让它工作?
您将在下面找到代码。
using System;
using System.Diagnostics;
using System.Threading;
namespace LinkedList
{
public class Node<T> where T : IComparable
{
public T Value;
public Node<T> Next { get; set; }
public Node(T value, Node<T> next)
{
this.Value = value;
this.Next = next;
}
}
public class SortedLinkedList<T> where T : IComparable
{
public Node<T> start;
public SortedLinkedList()
{
start = null;
}
public SortedLinkedList(Node<T> node)
{
start = node;
}
public void Insert(T value)
{
if ( this.start == null )
{
this.start = new Node<T>(value, this.start);
}
Node<T> curr = this.start;
while ( curr != null )
{ curr = curr.Next;}
curr.Next = new Node<T>(value,curr.Next);
}
}
public class Program
{
public static void Main(string[] args)
{
var list =
new SortedLinkedList<int>(
new Node<int>(
5, new Node<int>(
7, new Node<int>(
21, new Node<int>(
30, null)
)
)
)
);
list.Insert(12);
var list2 = new SortedLinkedList<string>();
list2.Insert("hello");
}
}
}
【问题讨论】:
-
感谢您的回复。我知道 NullReferenceException 是什么。我不知道为什么我在我的代码中得到它。
标签: c# .net list data-structures