我正在编写自己的单链表以用于学习目的,但我坚持使用“获取”方法。
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);
}
它似乎有效,但是当我想知道列表中最后一个元素的值时,它给了我一个NullReferenceException
Any way to prevent this?