【问题标题】:Java - Move object to front of LinkedListJava - 将对象移动到 LinkedList 的前面
【发布时间】:2014-03-30 19:47:23
【问题描述】:

我正在遍历 LinkedList 中的对象列表,搜索第一个满足某些条件的对象。找到后,我想将其移至列表的前面,以减少在列表中搜索常用对象的平均时间。

我正在尝试做的伪代码示例:

for(Object thing:list){
    if(ThisIsTheObjectWeAreLookingFor(thing)){
        list.RemoveCurrentLinkedListNode();
        list.addFirst(thing);
        return thing;
    }
}

我知道我可以使用 remove(Object) 或 remove(index) 方法,但这会更慢。基本上如此,取决于列表中元素的数量。 (因为这些方法必须第二次遍历列表。)

【问题讨论】:

标签: java data-structures linked-list


【解决方案1】:
Iterator it = list.iterator();
while (it.hasNext()) {
    Object thing = it.next();
    if (ThisIsTheObjectWeAreLookingFor(thing)) {
        it.remove();
        list.addFirst(thing);
        return thing;
    }
}

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-25
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多