[英]How to get the index of an element in a singly linked list?
I have two classes: 我有两节课:
SLList for methods (private SLElement _root) 方法的SLList(专用SLElement _root)
SLElement for creating new elements for the list. SLElement用于为列表创建新元素。 (public int _value; public SLElement _next)
(public int _value; public SLElement _next)
I have finished the add-method: 我已经完成了添加方法:
public void Add(int value)
{
SLElement addNewElement = new SLElement();
addNewElement._value = value;
SLElement rootCopy = _root;
_root = addNewElement;
addNewElement._next = rootCopy;
Console.WriteLine(addNewElement._value);
}
So now I want a remove-function. 所以现在我想要一个删除功能。 I already got it working that it removes an element with a specific value, but I want it so that it removes an element with an specific index.
我已经可以删除具有特定值的元素,但是我希望它可以删除具有特定索引的元素。 How can I find out the index of the elements in my list?
如何找到列表中元素的索引?
您需要从头开始遍历列表,一路计数。
Unless you have a strong reason for which you would like to create your own, I believe you should go for a LinkedList 除非您有充分的理由要创建自己的理由,否则我相信您应该选择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());
Loop throw index times and find the element 循环抛出索引时间并找到元素
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.