移动列表元素 [英] Move elements in list
问题描述
我宣布下列对象
名单,其中,串>表= {凯特,约翰,禄,夏娃,雨果};
我想移动夏娃在我的名单前面?我怎样才能做到这一点。我不能重新安排其他元素!
在输出我想要得到这个
夏娃,凯特,约翰,禄,雨果
list.Remove(夏娃); //删除列表中的第一个夏娃元素
list.Insert(0,夏娃); //插入夏娃在列表中的第一个位置
然而,如果你的列表中包含多个夏娃S,要求删除(夏娃)将仅删除了夏娃中第一次出现。
和你要知道,在列表的开头插入的元素是一个昂贵的操作。因为已经在列表的所有元素都被移位。
更新
由于@AlvinWong评论,的LinkedList<字符串>
是一个很好的解决方案插入一个元素时,为了避免这种开销。该插入
运行在O(1)完成的(O(NI)在列表
)。最大的缺点的LinkedList<字符串>
是访问我
个元素是O(I)的操作( O(1)在列表
)。
I declare following object
List<string> list = {"Kate", "John", "Paul", "Eve", "Hugo"};
I would like to move "Eve" at front of my list? How can I do that. I must not to reorder other elements!
At output I want to get this
"Eve", "Kate", "John", "Paul", "Hugo"
list.Remove("Eve"); // Removes the first "Eve" element in the list
list.Insert(0, "Eve"); // Inserts "Eve" at the first position in the list
However, if your list contains multiple "Eve"s, calling Remove("Eve") will only remove the first occurrence of "Eve".
And you have to know that inserting element at the beginning of a list is an expensive operation. Because all elements already in the list have to be shifted.
UPDATE
As @AlvinWong commented, LinkedList<string>
is a very good solution to avoid this overhead when inserting an element. The Insert
operation is done in O(1) (O(n-i) in a List
). The major drawback of LinkedList<string>
is that accessing the i
th element is an operation in O(i) (O(1) in a List
).
这篇关于移动列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!