我看到以下错误:
对象引用未设置为对象的实例!
在调用方法之前检查以确定对象是否为空!
我是C#的新手,我为Sorted Linked Lists制作了一个程序。 这是错误发生的代码!
public void Insert(double data)
{
Link newLink = new Link(data);
Link current = first;
Link previous = null;
if (first == null)
{
first = newLink;
}
else
{
while (data > current.DData && current != null)
{
previous = current;
current = current.Next;
}
previous.Next = newLink;
newLink.Next = current;
}
}
它表示当前引用为空while (data > current.DData && current != null)
,但我分配了它:current = first;
其余的是本程序的完整代码!
class Link
{
double dData;
Link next=null;
public Link Next
{
get { return next; }
set { next = value; }
}
public double DData
{
get { return dData; }
set { dData = value; }
}
public Link(double dData)
{
this.dData = dData;
}
public void DisplayLink()
{
Console.WriteLine("Link : "+ dData);
}
}
class SortedList
{
Link first;
public SortedList()
{
first = null;
}
public bool IsEmpty()
{
return (this.first == null);
}
public void Insert(double data)
{
Link newLink = new Link(data);
Link current = first;
Link previous = null;
if (first == null)
{
first = newLink;
}
else
{
while (data > current.DData && current != null)
{
previous = current;
current = current.Next;
}
previous.Next = newLink;
newLink.Next = current;
}
}
public Link Remove()
{
Link temp = first;
first = first.Next;
return temp;
}
public void DisplayList()
{
Link current;
current = first;
Console.WriteLine("Display the List!");
while (current != null)
{
current.DisplayLink();
current = current.Next;
}
}
}
class SortedListApp
{
public void TestSortedList()
{
SortedList newList = new SortedList();
newList.Insert(20);
newList.Insert(22);
newList.Insert(100);
newList.Insert(1000);
newList.Insert(15);
newList.Insert(11);
newList.DisplayList();
newList.Remove();
newList.DisplayList();
}
}
答案 0 :(得分:1)
你可能假设while循环在第一次迭代时破坏了,而不是它在while循环中的赋值最终会破坏它。
最终根据您的代码,当前为NULL,您甚至测试它 - 将其更改为此,它应该没问题:
while (current != null && data > current.DData)
{
previous = current;
current = current.Next;
}
答案 1 :(得分:0)
同意你已经完成了
current = first;
但是你的班级首先是空的
class SortedList
{
Link first;
请为first
分配一些内容,否则它将为空