Object reference not set to an instance of an object- Linked List Example
- by Zoro Roronoa
I am seeing following errors :
Object reference not set to an instance of an object!
Check to determinate if the object is null before calling the method!
I'am new with C#,and I made a program for Sorted Linked Lists.
Here is the code where the error comes!
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;
}
}
It says that the current referenc is null while (data current.DData && current != null), but I assigned it
current = first;
Please Help !
The rest is the complete code of the Program!
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();
}
}