0

我正在编写自己的单链表以用于学习目的,但我坚持使用“获取”方法。

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?

4

2 回答 2

2

因为它从 0 开始,所以您的循环应该在(ie )for()时停止:i = index - 1i < index

for (int i = 0; i < index; i++)

第一个元素在位置 0,所以最后一个元素在 position index - 1

于 2012-12-10T10:24:35.687 回答
1

我现在让它像这样工作:

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;
    }
  }
  Console.WriteLine("Index {0} has the value {1}", index, curr._value);
  if (prev == null) return;
  prev._next = curr._next;
  curr._next = _root;
}

这对我有用

于 2012-12-10T11:43:09.327 回答