I am writing my own single linked list for learning purposes, but I stuck at the “Get” Method.
public void Get(int index)
{
SLElement curr = _root;
SLElement prev = _root._next;
for (int i = 0; i <= index; i++)
{
while (curr._next != null)
{
if (curr == null) return;
prev = curr;
curr = curr._next;
}
}
prev._next = curr._next;
curr._next = prev;
Console.WriteLine("Index {0} has the value {1}", index, curr._value);
}
It seems to work, but when I want to know the value of the last element in the list, it gives me a NullReferenceException
Any way to prevent this?
Because it starts at 0, your
for()loop should stop wheni = index - 1(iei < index) :The first element is at position 0, so the last one is at position
index - 1.