Pin*_*ple 5 java linked-list data-structures
我正在遍历LinkedList中的对象列表,搜索满足某些条件的第一个对象.一旦找到,我想将其移动到列表的前面,以减少在列表中搜索常用搜索对象所花费的平均时间.
Psuedocode我正在尝试做的例子:
for(Object thing:list){
if(ThisIsTheObjectWeAreLookingFor(thing)){
list.RemoveCurrentLinkedListNode();
list.addFirst(thing);
return thing;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用remove(Object)或remove(index)方法,但这会慢一些.基本上如此,取决于列表中的元素数量.(因为这些方法必须第二次遍历列表.)
Iterator it = list.iterator();
while (it.hasNext()) {
Object thing = it.next();
if (ThisIsTheObjectWeAreLookingFor(thing)) {
it.remove();
list.addFirst(thing);
return thing;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4489 次 |
| 最近记录: |