【问题标题】:How to get the index of an element in a singly linked list?如何获取单链表中元素的索引?
【发布时间】:2012-12-06 14:59:09
【问题描述】:

我有两个班级:

方法的 SLList(私有 SLElement _root)

SLElement 用于为列表创建新元素。 (public int _value; public SLElement _next)

我已经完成了添加方法:

public void Add(int value)
{
  SLElement addNewElement = new SLElement();
  addNewElement._value = value;
  SLElement rootCopy = _root;
  _root = addNewElement;
  addNewElement._next = rootCopy;
  Console.WriteLine(addNewElement._value);
}

所以现在我想要一个删除功能。我已经让它工作了,它删除了一个具有特定值的元素,但我想要它,以便它删除一个具有特定索引的元素。如何找出列表中元素的索引?

【问题讨论】:

  • 这是作业吗?有什么理由不使用 c# 链表?您应该跳过 i 个元素,并删除当前元素
  • 当我在没有下一个元素的 SLElement 上调用 _next 会发生什么?
  • 你得到一个 NullReferenceException

标签: c# indexing stack singly-linked-list


【解决方案1】:

你需要从头开始遍历你的列表,一路数数。

【讨论】:

    【解决方案2】:

    除非你有充分的理由想要创建自己的,我相信你应该去LinkedList

    var list = new LinkedList<SLElement>();
    
    list.AddAfter(list.AddFirst(new SLElement()), new SLElement());
    
    list.Remove(list.Select((i, j) => new { i, j })
        .Where(j => j.j == 0)//remove the first node
        .Select(i => i.i)
        .FirstOrDefault());
    

    【讨论】:

    • 不,这不是家庭作业,我 16 岁,刚开始接受培训,现在我必须自己制作一个链接列表才能了解它是如何工作的 :)
    【解决方案3】:

    循环抛出索引次数并找到元素

    public SLElement Remove(int index)
    {
        SLElement prev = _root;
        if(prev == null) return null; //or throw exception
        SLElement curr = _root.next;
        for(int i = 1; i < index; i++)
        {
          if(curr == null) return null; //or throw exception
          prev = curr;
          curr = curr.next;
        }
        prev.next = curr.next; //set the previous's node point to current's next node
        curr.next = null;
        return curr;
    }
    

    【讨论】:

    • 这真的帮了我很多,谢谢:) 还有一件事:我想你可能想改变“return rtn;” “返回当前;” ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多